【问题标题】:How to receive data from multiple WebSockets asynchronously in Python?如何在 Python 中异步接收来自多个 WebSocket 的数据?
【发布时间】:2018-08-17 15:58:57
【问题描述】:

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

【问题讨论】:

    标签: python asynchronous websocket python-asyncio


    【解决方案1】:

    对于发现此问题的任何人,我都找到了答案。仅适用于 > 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())
    

    【讨论】:

    • 我正在寻找与自动连接功能类似的东西,以确保客户端始终连接到 websocket 服务器。如果连接已关闭,我希望客户端重新建立与服务器的连接。例如wss://api.foobar.com:8765 websocket 服务器已重新启动。客户端应该在几个间隔后自动重新连接。你能帮忙说明如何编写这样的功能吗?
    【解决方案2】:

    代替:

    connections = set()
    

    我会列出它:

    connections = []
    connections = ["wss://api.foo.com:8765"]
    connections.append ("wss://api.bar.com:8765")
    connections.append ("wss://api.foobar.com:8765")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2011-12-20
      相关资源
      最近更新 更多