python
network_error
ai_generated
true
websockets.exceptions.ConnectionClosedError: WebSocket connection closed unexpectedly
ID: python/starlette-websocket-disconnect-error
80%Fix Rate
84%Confidence
0Evidence
2024-11-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
Root Cause
Starlette WebSocket 连接因网络问题或客户端断开而意外关闭
generic中文
Starlette WebSocket 连接因网络问题或客户端断开而意外关闭
Workarounds
-
90% success 捕获异常并优雅地关闭连接
try: await websocket.receive_text() except WebSocketDisconnect: await websocket.close() -
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:
-
忽略异常并继续发送消息
95% fail
连接已关闭,发送消息会引发更多错误
-
无限重试连接而不检查状态
80% fail
可能导致无限循环和资源浪费