# WebSocket 握手错误：400 错误请求

- **ID:** `communication/websocket-handshake-400-bad-request`
- **领域:** communication
- **类别:** protocol_error
- **错误码:** `400`
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

WebSocket 握手失败，因为服务器拒绝升级请求，原因是缺少或无效的标头，例如缺少 'Sec-WebSocket-Key' 或不受支持的 'Origin'。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| WebSocket (RFC 6455) | active | — | — |
| Node.js 18 | active | — | — |
| Python websockets 12.0 | active | — | — |
| Nginx 1.24 | active | — | — |

## 解决方案

1. ```
   Inspect and fix the 'Origin' header in the client request. For example, in JavaScript: `const socket = new WebSocket('wss://example.com/socket', { headers: { Origin: 'https://example.com' } });` Ensure the Origin matches the server's allowed list.
   ```
2. ```
   Add the 'Sec-WebSocket-Key' header manually if the library omits it. In Python with websockets: `import base64, os; key = base64.b64encode(os.urandom(16)).decode(); headers = {'Sec-WebSocket-Key': key}` and pass to the client.
   ```
3. ```
   Check the server-side Nginx configuration for WebSocket support: ensure `proxy_set_header Upgrade $http_upgrade;` and `proxy_set_header Connection "upgrade";` are present in the location block.
   ```

## 无效尝试

- **Disable header validation in the WebSocket client library** — Disabling the WebSocket library's built-in header validation does not fix the missing or invalid headers; the server still requires them for the upgrade. (90% 失败率)
- **Switch to a different WebSocket client library (e.g., from ws to socket.io)** — Switching to a different WebSocket library without addressing the header issue just moves the problem; the new library will still fail if the headers are wrong. (85% 失败率)
- **Increase the WebSocket connection timeout** — Increasing the timeout does not help because the error is immediate upon handshake, not a timeout issue. (95% 失败率)
