python network_error ai_generated true

starlette.websockets.WebSocketDisconnect: 1006

ID: python/fastapi-websocket-disconnect-loop

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-09-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100+ active — — —
0.110+ active — — —

Root Cause

Client closed the socket without a close frame; server loop keeps calling receive/send without catching WebSocketDisconnect.

generic

中文

客户端未发送关闭帧即关闭套接字;服务端循环继续调用 receive/send 而未捕获 WebSocketDisconnect。

Workarounds

  1. 93% success
    try:
        while True:
            msg = await ws.receive_text()
            await ws.send_text(msg)
    except WebSocketDisconnect:
        pass
  2. 88% success
    Use ws.iter_text() and break on disconnect; send a ping interval for liveness.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Hides real errors and leaks sockets; CPU spins on reconnect storms.

  2. 75% fail

    close() on a dead socket raises again.