# WebSocket 关闭代码 1002：协议错误

- **ID:** `api/websocket-close-code-1002-protocol-error`
- **领域:** api
- **类别:** protocol_error
- **错误码:** `1002`
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

WebSocket 帧格式错误或包含无效数据，例如保留操作码或分片控制帧。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| RFC 6455 | active | — | — |
| ws library 8.x | active | — | — |
| Socket.IO 4.x | active | — | — |
| Spring WebSocket 6.0 | active | — | — |
| Node.js ws 8.14+ | active | — | — |

## 解决方案

1. ```
   Validate that control frames (e.g., ping, pong, close) are not fragmented. In JavaScript, ensure you are not sending a fragmented ping frame:
// Bad: Sending a fragmented ping
ws.send(Buffer.from('ping'), { fin: false, opcode: 0x9 }); // Wrong!
// Good: Send a complete ping frame
ws.ping(); // Uses correct non-fragmented frame
   ```
2. ```
   Check for reserved opcodes (0x3-0x7, 0xB-0xF) in the frame. If using a custom WebSocket library, ensure opcode is in {0x0, 0x1, 0x2, 0x8, 0x9, 0xA}.
   ```

## 无效尝试

- **** — The error is immediate and not related to timeouts. (90% 失败率)
- **** — The root cause is in the client's frame construction, not server state. (80% 失败率)
