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

如何在Python中异步接收来自多个WebSocket的数据?,python,asynchronous,websocket,python-asyncio,Python,Asynchronous,Websocket,Python Asyncio,我目前正在尝试使用。如果其他图书馆更适合这个目的,请告诉我 鉴于这些功能: def handle_message(msg): # do something async def consumer_handler(websocket, path): async for message in websocket: handle_message(message) 如何(无限期)连接到多个WebSocket?下面的代码可以工作吗 import asyncio impor

我目前正在尝试使用。如果其他图书馆更适合这个目的,请告诉我

鉴于这些功能:

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

对于找到这个的人,我找到了答案。我相信只有在>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())

对于找到这个的人,我找到了答案。我相信只有在>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())