python network_error ai_generated true

RuntimeError: WebSocket connection closed unexpectedly

ID: python/starlette-websocket-connection-closed

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-08-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

客户端或服务器端非正常关闭WebSocket连接

generic

中文

客户端或服务器端非正常关闭WebSocket连接

Workarounds

  1. 90% success 在WebSocket处理中添加重连逻辑
    async def websocket_endpoint(websocket):
        await websocket.accept()
        try:
            while True:
                data = await websocket.receive_text()
        except WebSocketDisconnect:
            print('Client disconnected')
  2. 85% success 使用心跳检测保持连接
    async def heartbeat(websocket):
        while True:
            await asyncio.sleep(30)
            await websocket.send_text('ping')

Dead Ends

Common approaches that don't work:

  1. 尝试重新连接而不处理关闭原因 50% fail

    未处理关闭原因可能导致无限重连

  2. 在接收消息时不检查连接状态 40% fail

    已关闭的连接无法接收消息