Python websockets ping / pong / keep-alive错误

hrirmatl  于 2023-06-23  发布在  Python
关注(0)|答案(1)|浏览(476)

我有一个从WebSocket服务器阅读消息的简单脚本,我不完全理解keep-alive系统。我得到了两个意思几乎相同的错误sent 1011 (unexpected error) keepalive ping timeout; no close frame receivedno close frame received or sent
使用websockets模块。链接到docs
我想知道我的工作是什么时候发送ping,什么时候发送pong,或者我是否应该将超时时间更改为更长的时间,因为我将同时运行多个连接(到同一服务器但不同的通道)。
我试过运行另一个asyncio任务,它每10到20秒ping一次服务器,只有在我收到一个数据包后才回复(在我的情况下,可以间隔1秒,或者我可以在第二天收到一个新的数据包。使用普通的websocket.ping()和自定义有效负载(heartbeat json字符串{"event": "bts:heartbeat"}
我可以看到的一个解决方案是在我得到错误后重新打开连接,但感觉不对。

async with websockets.connect(self.ws,) as websocket:
        packet = {
            "event": "bts:subscribe",
            "data": ...,
        }
        await websocket.send(json.dumps(packet))
        await websocket.recv() # reply 
       
        try:
            async for message in websocket:
                tr = json.loads(message)
                await self.send(tr)
                packet = {"event": "bts:heartbeat"}
                await websocket.pong(data=json.dumps(packet))

        except Exception as e:  # websockets.ConnectionClosedError:
            await self.send_status(f"Suscription Error: {e}", 0)
4dc9hkyq

4dc9hkyq1#

Keep-alive数据包由库自动发送(请参阅https://websockets.readthedocs.io/en/latest/topics/timeouts.html#keepalive-in-websockets),因此您不需要自己执行此操作。
在您的情况下,服务器似乎没有及时响应客户端的“ping”。这个FAQ条目及其捕获ConnectionClosed的建议看起来很相关。

相关问题