diff --git a/server/Websocket.py b/server/Websocket.py index 407038c..1d77e3f 100644 --- a/server/Websocket.py +++ b/server/Websocket.py @@ -1,21 +1,34 @@ -import websockets; -import asyncio; +import websockets +import asyncio +connected = set() async def handler(websocket): - while True: - #Save the incoming message in variable message. - message = await websocket.recv() - print(message) + # Register. + connected.add(websocket) + try: + while True: + message = await websocket.recv() + print(message) + await broadcast(message) + except websockets.ConnectionClosedOK: + print("Client disconnected") + finally: + connected.remove(websocket) +async def broadcast(message): + if connected: # asyncio.wait doesn't accept an empty list + await asyncio.wait([ws.send(message) for ws in connected]) + +async def sendClientId(): + if connected: # asyncio.wait doesn't accept an empty list + await asyncio.wait([ws.send(message) for ws in connected]) async def main(): - async with websockets.serve(handler, "145.92.8.114" , 8001): + async with websockets.serve(handler, "0.0.0.0", 8001): await asyncio.Future() # run forever - if __name__ == "__main__": - asyncio.run(main()) - + asyncio.run(main()) #https://websockets.readthedocs.io/en/stable/reference/sync/server.html#websockets.sync.server.serve \ No newline at end of file