WebSocket 可扩展架构与断线重连:心跳保活、指数退避与消息路由技术背景WebSocket 提供低延迟双向通信,但需要心跳保活与断线重连策略确保稳定性。可扩展的消息路由与会话管理能支撑高并发实时场景,提升整体可靠性。核心内容前端客户端:心跳与重连class WSClient { private ws: WebSocket | null = null; private url: string; private backoff = 1000; private hbTimer: any = null; private subs = new Map<string, (data: any) => void>(); constructor(url: string) { this.url = url; } connect() { this.ws = new WebSocket(this.url); this.ws.onopen = () => { this.backoff = 1000; this.heartbeat(); }; this.ws.onmessage = (e) => { try { const msg = JSON.parse(e.data); const cb = this.subs.get(msg.topic); if (cb) cb(msg.payload); } catch {} }; this.ws.onclose = () => { this.scheduleReconnect(); }; this.ws.onerror = () => { this.ws?.close(); }; } subscribe(topic: string, cb: (data: any) => void) { this.subs.set(topic, cb); } publish(topic: string, payload: any) { this.ws?.send(JSON.stringify({ topic, payload })); } heartbeat() { clearInterval(this.hbTimer); this.hbTimer = setInterval(() => { this.ws?.send(JSON.stringify({ type: 'ping', ts: Date.now() })); }, 15000); } scheduleReconnect() { clearInterval(this.hbTimer); setTimeout(() => { this.backoff = Math.min(this.backoff * 2, 30000); this.connect(); }, this.backoff); } } 后端(Node/ws)会话管理与路由import { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 8080 }); const topics = new Map<string, Set<any>>(); wss.on('connection', (ws) => { ws.on('message', (data) => { try { const msg = JSON.parse(String(data)); if (msg.type === 'ping') { ws.send(JSON.stringify({ type: 'pong', ts: Date.now() })); return; } if (msg.topic && msg.payload !== undefined) { if (!topics.has(msg.topic)) topics.set(msg.topic, new Set()); const subs = topics.get(msg.topic)!; subs.add(ws); for (const client of subs) { if (client.readyState === 1) client.send(JSON.stringify({ topic: msg.topic, payload: msg.payload })); } } } catch {} }); ws.on('close', () => { for (const subs of topics.values()) subs.delete(ws); }); }); 技术验证参数在 Chrome 128/Edge 130 + Node 20(局域网 1Gbps):重连恢复时间:P95 < 2s,P99 < 5s心跳超时断开检测:≤ 45s广播吞吐:≥ 50k msg/min(64B 文本)连接稳定率:≥ 99%应用场景实时行情、聊天与协作编辑告警与通知通道直播弹幕与互动类应用最佳实践采用指数退避控制重连频率心跳与服务端超时配合,避免僵尸连接主题路由与权限控制,隔离频道与用户压测与限流策略保障稳定性

发表评论 取消回复