Search code examples
pythonwebsocketserverfastapi

Data exchange between websocket clients and server


I have a system that has a fastAPI server, a python client implemented on Raspberry and Javascript clients for the user interface. Data is sent from python client to server then forwarded to Js client and vice versa. I established the connection between the server and each type of client but when sending from a client-side to the server, it just send back to that client and the rest ones receive nothing. What is the proper way to deal with this problem? Hope for your help. Thanks.


Solution

  • The problem with websocket is it doesn't support broadcasting. You can store somewhere list of connected clients and iterate over them to send a message

    CLIENTS = set()
    async def broadcast():
        while True:
            await asyncio.gather(
                *[ws.send("woof") for ws in CLIENTS],
                return_exceptions=False,
            )
            await asyncio.sleep(2)
    
    asyncio.create_task(broadcast())
    
    async def handler(websocket, path):
        CLIENTS.add(websocket)
        try:
            async for msg in websocket:
                pass
        finally:
            CLIENTS.remove(websocket)
    
    start_server = websockets.serve(handler, ...)
    
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
    

    You can read more information here

    However my recommendation is to use socket.io. With it you can create rooms and send data to all clients that entered room with single emit.