python - 使用 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 接收以避免丢失消息?
谢谢您的回答!
解决方案
好的我明白了。我的函数只运行一次,下一条消息没有缓冲。下面的代码解决了这个问题:
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
推荐阅读
- r - 如何在R中按日期平均多个变量?
- typescript - 覆盖(更改参数)超类方法的可能性
- javascript - javascript中的快速多边形联合
- google-apps-script - 自行组织 Google Apps 脚本
- django - Django - ConnectionAbortedError: [WinError 10053] 已建立的连接被主机中的软件中止
- python - TypeError:“NoneType”对象在 send_mail 中不可迭代?
- android - 如何使用类别显示 Firebase 数据库中的工具栏标题?我被困住了
- powershell - 删除文件夹和文件但排除子文件夹
- javascript - 内联样式 CSP 违规 tawk.to 嵌入式聊天小部件
- .htaccess - htaccess 重定向子目录中的所有文件以重定向到该子目录索引页