如何在Python中异步地从多个WebSockets接收数据?

时间:2018-08-17 15:58:58

标签: python asynchronous websocket python-asyncio

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

提供以下功能:

def handle_message(msg):
    # do something

async def consumer_handler(websocket, path):
    async for message in websocket:
        handle_message(message)

如何(无限期)连接到多个websocket?下面的代码可以工作吗?

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())

1 个答案:

答案 0 :(得分:0)

对于任何发现此问题的人,我都找到了答案。我相信只能在> 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())