WebSocket 是现代实时应用的核心技术。 Claude Code 能帮你快速搭建聊天室、实时协作、 股票行情推送等 WebSocket 应用,少踩坑、写对代码。
Claude Code 在 WebSocket 开发中的优势
适合让 Claude Code 处理的 WebSocket 难点:
连接管理(心跳/重连/断线检测)
广播与房间管理(一对一/一对多/群组)
认证鉴权(JWT over WebSocket)
并发连接下的状态同步
错误处理和优雅关闭
场景一:Node.js WebSocket 服务器
Prompt:
用 Node.js + ws 库写一个 WebSocket 聊天室服务器:
- 支持多个房间(room),用户加入指定房间
- 服务端广播(所有人)和私信(指定用户)
- JWT 鉴权(握手阶段验证 token)
- 心跳检测(30s ping/pong,超时断开)
- 断线时通知房间内其他人
Claude Code 生成的核心结构:
javascript
const WebSocket = require('ws')
const jwt = require('jsonwebtoken')
const wss = new WebSocket.Server({ port: 8080 })
// rooms: Map<roomId, Set<clientId>>
const rooms = new Map()
// clients: Map<clientId, { ws, userId, rooms }>
const clients = new Map()
wss.on('connection', (ws, req) => {
// 1. 从 URL 参数获取 token
const token = new URL(req.url, 'http://x').searchParams.get('token')
let userId
try {
userId = jwt.verify(token, process.env.JWT_SECRET).sub
} catch {
ws.close(4001, 'Unauthorized')
return
}
const clientId = crypto.randomUUID()
clients.set(clientId, { ws, userId, rooms: new Set() })
// 2. 心跳检测
ws.isAlive = true
ws.on('pong', () => { ws.isAlive = true })
ws.on('message', (data) => {
const msg = JSON.parse(data)
handleMessage(clientId, msg)
})
ws.on('close', () => {
handleDisconnect(clientId)
})
})
// 心跳定时器
const heartbeat = setInterval(() => {
wss.clients.forEach(ws => {
if (!ws.isAlive) { ws.terminate(); return }
ws.isAlive = false
ws.ping()
})
}, 30000)场景二:前端 WebSocket 客户端(带自动重连)
Prompt:
写一个 React hooks 封装 WebSocket 客户端:
- 自动重连(指数退避,最多重试 5 次)
- 连接状态管理(connecting/connected/reconnecting/closed)
- 消息队列(断线时缓存消息,重连后发送)
- 返回 sendMessage、lastMessage、connectionStatus
- TypeScript 类型完整
Claude Code 生成的 Hook:
typescript
function useWebSocket(url: string) {
const [status, setStatus] = useState<'connecting'|'connected'|'reconnecting'|'closed'>('connecting')
const [lastMessage, setLastMessage] = useState<MessageEvent | null>(null)
const wsRef = useRef<WebSocket | null>(null)
const retryCount = useRef(0)
const pendingQueue = useRef<string[]>([])
const connect = useCallback(() => {
const ws = new WebSocket(url)
wsRef.current = ws
ws.onopen = () => {
setStatus('connected')
retryCount.current = 0
// 发送缓存的消息
pendingQueue.current.forEach(msg => ws.send(msg))
pendingQueue.current = []
}
ws.onmessage = setLastMessage
ws.onclose = () => {
if (retryCount.current < 5) {
setStatus('reconnecting')
const delay = Math.min(1000 * 2 ** retryCount.current, 30000)
retryCount.current++
setTimeout(connect, delay)
} else {
setStatus('closed')
}
}
}, [url])
const sendMessage = useCallback((msg: string) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(msg)
} else {
pendingQueue.current.push(msg)
}
}, [])
useEffect(() => { connect(); return () => wsRef.current?.close() }, [connect])
return { sendMessage, lastMessage, status }
}场景三:FastAPI WebSocket(Python 后端)
Prompt:
用 FastAPI 写一个实时协作文档编辑的 WebSocket 后端:
- 多人同时编辑同一文档
- 广播每个用户的光标位置和编辑内容
- 使用 Operational Transformation 简化版(最后写入者胜出)
- Redis pub/sub 支持多进程广播(多个 worker 实例)
场景四:Nginx WebSocket 反向代理
Prompt:
帮我配置 Nginx,把 wss://api.example.com/ws
反向代理到后端的 ws://127.0.0.1:8080,
处理好 WebSocket 升级握手和长连接超时。
Claude Code 生成的配置:
nginx
location /ws {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 3600s; # 1小时,防止长连接被断
proxy_send_timeout 3600s;
}常见问题排查 Prompt
[连接莫名断开]
WebSocket 连接在 60 秒左右自动断开,
但心跳 ping/pong 代码已经写了。
服务器是 Nginx 反向代理 + Node.js。
帮我分析可能的原因并给出排查步骤。
[消息顺序乱序]
多个客户端同时发消息时,
接收方有时会收到乱序的消息。
如何保证消息的有序性?
来源:Anthropic Claude Code 官方文档 - docs.anthropic.com/en/docs/claude-code