# aiohttp 客户端异常：无效的 WebSocket 握手

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

## 根因

服务器不支持 WebSocket 协议或握手响应格式错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.10 | active | — | — |
| 3.11 | active | — | — |

## 解决方案

1. **Verify server WebSocket endpoint and use correct URL scheme (ws:// or wss://)** (90% 成功率)
   ```
   async with session.ws_connect('wss://example.com/ws') as ws:
    async for msg in ws:
   ```
2. **Fall back to HTTP long polling if WebSocket fails** (80% 成功率)
   ```
   try:
    async with session.ws_connect(url) as ws:
        # use websocket
except aiohttp.WSServerHandshakeError:
    # fallback to polling
   ```

## 无效尝试

- **Using a different WebSocket library without checking server compatibility** — The server itself may not support WebSocket, so changing the client library won't help. (60% 失败率)
- **Adding custom headers to the handshake request** — If the server rejects WebSocket at the protocol level, custom headers won't fix it. (50% 失败率)
