小编Blu*_*ile的帖子

如何在 Python 中异步接收来自多个 WebSocket 的数据?

我目前正在尝试使用websockets 库。如果另一个图书馆更适合此目的,请告诉我。

鉴于这些功能:

def handle_message(msg):
    # do something

async def consumer_handler(websocket, path):
    async for message in websocket:
        handle_message(message)
Run Code Online (Sandbox Code Playgroud)

我如何(无限期地)连接到多个 websockets?下面的代码会起作用吗?

import asyncio
import websockets


connections = set()
connections.add(websockets.connect(consumer_handler, 'wss://api.foo.com', 8765))
connections.add(websockets.connect(consumer_handler, 'wss://api.bar.com', 8765))
connections.add(websockets.connect(consumer_handler, 'wss://api.foobar.com', 8765))

async def handler():
    await asyncio.wait([ws for ws in connections])

asyncio.get_event_loop().run_until_complete(handler())
Run Code Online (Sandbox Code Playgroud)

python asynchronous websocket python-asyncio

1
推荐指数
1
解决办法
4032
查看次数

标签 统计

asynchronous ×1

python ×1

python-asyncio ×1

websocket ×1