# WebSocket关闭代码1008：策略违规

- **ID:** `api/websocket-close-code-1008-policy-violation`
- **领域:** api
- **类别:** protocol_error
- **错误码:** `1008`
- **验证级别:** ai_generated
- **修复率:** 75%

## 根因

服务器因策略违规关闭WebSocket连接，例如无效身份验证、不支持的子协议或消息格式违规。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| WebSocket RFC 6455 | active | — | — |
| Socket.IO 4.7.0 | active | — | — |
| ws@8.16.0 (Node.js) | active | — | — |
| Spring WebSocket 6.1.0 | active | — | — |

## 解决方案

1. ```
   重新连接前检查并刷新身份验证令牌：`ws = new WebSocket('wss://api.example.com/ws', { headers: { Authorization: `Bearer ${newToken}` } })`
   ```
2. ```
   验证子协议是否与服务器期望匹配：`ws = new WebSocket('wss://api.example.com/ws', ['graphql-ws'])`
   ```
3. ```
   确保消息格式符合预期（例如JSON）：`ws.send(JSON.stringify({ type: 'subscribe', channel: 'updates' }))`
   ```

## 无效尝试

- **** — Reconnecting without addressing the underlying policy violation (e.g., expired token) (85% 失败率)
- **** — Assuming it's a network timeout and increasing timeout values (60% 失败率)
- **** — Changing WebSocket URL path without verifying authentication credentials (70% 失败率)
