I am using these docs to get to know websockets
from Python.
When everything that is happening 'inside' those async
methods, it works fine, but how can I send a message outside of that? In my specific example, I am getting a button_pressed
event from a GPIO pin on a Raspberry PI, and I want to send all connected users a message that that button was pressed:
import asyncio
import websockets
import gpiozero
USERS = set()
def button_pressed():
print("Doorbell rang!")
if USERS:
for user in USERS:
print(f"Sending ring to {user}")
asyncio.wait(user.send("ring"))
button = gpiozero.Button(3)
button.when_pressed = button_pressed
def register(ws):
USERS.add(ws)
def unregister(ws):
USERS.remove(ws)
async def doorbellsocket(websocket, path):
register(websocket)
try:
async for message in websocket:
print(f"Received message: {message}. Ignored.")
finally:
unregister(websocket)
print(f"Starting doorbellserv on {settings.host}:{settings.port}")
start_server = websockets.serve(doorbellsocket, settings.host, settings.port)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
The code runs, the button press event gets fired and Python says it sends something, but nothing arrives in my client, which is as simple as this:
function connectToServ() {
var socket = new WebSocket(url);
console.log("Connected to "+socket)
socket.onmessage = function(event) {
console.log(event.data);
};
}