# websockets.exceptions.ConnectionClosedError: WebSocket connection closed unexpectedly

- **ID:** `python/starlette-websocket-disconnect-error`
- **Domain:** python
- **Category:** network_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

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

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.10 | active | — | — |
| 3.11 | active | — | — |

## 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

- **忽略异常并继续发送消息** — 连接已关闭，发送消息会引发更多错误 (95% fail)
- **无限重试连接而不检查状态** — 可能导致无限循环和资源浪费 (80% fail)
