首页 > 解决方案 > 使用 python + asyncio + websockets 推送 = 丢失消息

问题描述

我正在尝试创建一个 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,它应该管理背压:在服务器繁忙时发送的消息(处理旧消息)被“缓冲”,很快就会被处理....

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

谢谢您的回答!

标签: pythonpython-3.xwebsocketpython-asynciopython-multithreading

解决方案


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

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

推荐阅读