python
network_error
ai_generated
true
starlette.websockets.WebSocketDisconnect: 1006
ID: python/fastapi-websocket-disconnect-loop
80%修复率
86%置信度
0证据数
2024-09-18首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.100+ | active | — | — | — |
| 0.110+ | active | — | — | — |
根因分析
客户端未发送关闭帧即关闭套接字;服务端循环继续调用 receive/send 而未捕获 WebSocketDisconnect。
English
Client closed the socket without a close frame; server loop keeps calling receive/send without catching WebSocketDisconnect.
解决方案
-
93% 成功率
try: while True: msg = await ws.receive_text() await ws.send_text(msg) except WebSocketDisconnect: pass -
88% 成功率
Use ws.iter_text() and break on disconnect; send a ping interval for liveness.
无效尝试
常见但无效的做法:
-
70% 失败
Hides real errors and leaks sockets; CPU spins on reconnect storms.
-
75% 失败
close() on a dead socket raises again.