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

Blu*_*ile 1 python asynchronous websocket python-asyncio

我目前正在尝试使用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)

Blu*_*ile 7

对于任何找到这个的人,我找到了答案。我相信只适用于 > Python 3.6.1。

import asyncio
import websockets

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

async def handle_socket(uri, ):
    async with websockets.connect(uri) as websocket:
        async for message in websocket:
            print(message)

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

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