简体   繁体   English

websocket客户端和服务器之间的数据交换

[英]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.我有一个系统,它有一个 fastAPI 服务器、一个在 Raspberry 上实现的 python 客户端和用于用户界面的 Javascript 客户端。 Data is sent from python client to server then forwarded to Js client and vice versa.数据从 python 客户端发送到服务器,然后转发到 Js 客户端,反之亦然。 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.我在服务器和每种类型的客户端之间建立了连接,但是当从客户端发送到服务器时,它只是发送回该客户端,而 rest 则什么也没有收到。 What is the proper way to deal with this problem?处理这个问题的正确方法是什么? Hope for your help.希望得到您的帮助。 Thanks.谢谢。

The problem with websocket is it doesn't support broadcasting. websocket 的问题是它不支持广播。 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 .但是我的建议是使用socket.io With it you can create rooms and send data to all clients that entered room with single emit.有了它,您可以创建房间并将数据发送给所有进入房间的客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM