python network_error ai_generated true

websockets.exceptions.ConnectionClosedError: WebSocket connection closed unexpectedly

ID: python/starlette-websocket-disconnect-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-11-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active
3.11 active

Root Cause

Starlette WebSocket 连接因网络问题或客户端断开而意外关闭

generic

中文

Starlette WebSocket 连接因网络问题或客户端断开而意外关闭

Workarounds

  1. 90% success 捕获异常并优雅地关闭连接
    try:
        await websocket.receive_text()
    except WebSocketDisconnect:
        await websocket.close()
  2. 85% success 实现心跳机制检测连接状态
    async def heartbeat():
        while True:
            await asyncio.sleep(30)
            await websocket.send_json({'type': 'ping'})

Dead Ends

Common approaches that don't work:

  1. 忽略异常并继续发送消息 95% fail

    连接已关闭,发送消息会引发更多错误

  2. 无限重试连接而不检查状态 80% fail

    可能导致无限循环和资源浪费