【问题标题】:push with python + asyncio + websockets = missing messages使用 python + asyncio + websockets 推送 = 丢失消息
【发布时间】:2019-01-07 15:22:59
【问题描述】:

我正在尝试创建一个 websocket 服务器,单个客户端将在该服务器上推送其消息(我知道这不是使用 websocket 的常用方式,但这部分不是我的选择)。为此,我正在使用 python 3.7 和websockets 7.0。

我的问题是:服务器没有收到客户端推送的大量消息。 这是我正在使用的简单代码。

import asyncio
import websockets


async def get_tag_data(websocket, path):
    # print('received')
    data = await websocket.recv()
    print(data)


loop = asyncio.get_event_loop()
anchors_server = websockets.serve(get_tag_data, 'localhost', 9001)
loop.run_until_complete(asyncio.gather(anchors_server))
loop.run_forever()

相反,当我尝试python-websocket-server(使用线程接收)时,我的所有消息都被正确接收。

据我了解 asyncio 和 websockets,它应该管理 backpressure:在服务器繁忙时发送的消息(处理旧消息)被“缓冲”,很快就会被处理....

我错过了什么?我是否需要使用 asyncio 线程化 websocket 接收以避免丢失消息?

感谢您的回答!

【问题讨论】:

    标签: python python-3.x websocket python-asyncio python-multithreading


    【解决方案1】:

    好的,我明白了。 我的函数只运行一次,下一条消息没有缓冲。下面的代码解决了这个问题:

    import asyncio
    import websockets
    import signal
    import sys
    
    async def get_tag_data(websocket, path):
        while True:
            async for data in websocket:
                print(data)
    
    loop = asyncio.get_event_loop()
    anchors_server = websockets.serve(get_tag_data, '', 9001)
    loop.run_until_complete(asyncio.gather(anchors_server))
    loop.run_forever()
    

    注意

    while True:
        async for data in websocket
    

    【讨论】:

      【解决方案2】:

      应该没有while循环。

      import asyncio
      import websockets
      import signal
      import sys
      
      async def get_tag_data(websocket, path):
          async for data in websocket:
              print(data)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-20
        • 2011-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多