# WebSocket连接正常关闭：收到1000 (OK)；然后发送1000 (OK)

- **ID:** `python/starlette-websocket-disconnect`
- **领域:** python
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

WebSocket连接被客户端或服务器正常关闭。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **Handle the close event gracefully and clean up resources.** (90% 成功率)
   ```
   async def websocket_endpoint(websocket):
    await websocket.accept()
    try:
        while True:
            data = await websocket.receive_text()
            await websocket.send_text(f"Echo: {data}")
    except websockets.exceptions.ConnectionClosed:
        print('Connection closed')
   ```
2. **Implement reconnection logic with exponential backoff.** (85% 成功率)
   ```
   import asyncio
async def connect():
    while True:
        try:
            async with websockets.connect('ws://...') as ws:
                await ws.send('hello')
        except websockets.exceptions.ConnectionClosed:
            await asyncio.sleep(1)
   ```

## 无效尝试

- **Assuming it's an error and trying to reconnect indefinitely.** — Normal closure is not an error; reconnecting without reason is wasteful. (60% 失败率)
- **Ignoring the close event and continuing to send messages.** — The connection is closed; sending messages will raise another error. (90% 失败率)
