还是报websockets.exceptions.ConnectionClosedError: sent 1011 (unexpected error) keepalive ping timeout; no close frame received
时间: 2024-03-03 09:50:12 浏览: 27
如果你仍然遇到了相同的错误,那么你可能需要检查一下客户端是否正确地处理了心跳包,以及是否及时回复了服务器发送的心跳包。
另外,你也可以考虑增加一些日志输出,以便更好地排查问题。以下是一个修改后的代码示例,增加了一些日志输出:
```python
import asyncio
import websockets
async def handle_client(websocket, path):
while True:
try:
message = await asyncio.wait_for(websocket.recv(), timeout=50)
print(f"Received message: {message}")
await websocket.send(f"Echoing back your message: {message}")
except asyncio.TimeoutError:
print("Sending keepalive ping...")
await websocket.ping() # 发送心跳包,保持连接状态
except websockets.exceptions.ConnectionClosedError:
print("Connection closed!")
break
async def main():
async with websockets.serve(handle_client, "localhost", 8000):
print("Server started!")
await asyncio.Future() # keep running until Ctrl-C
if __name__ == "__main__":
asyncio.run(main())
```
上述代码中,我们增加了一些针对不同情况的日志输出,以便更好地排查问题。你可以根据实际情况调整日志输出的内容。