引言
WebSocket 提供全双工连接,但可靠性和扩展性不会自动出现。必须显式处理连接建立、断线检测、重连、消息积压和跨实例分发。
连接生命周期
升级握手后要认证用户、绑定房间或主题,并注册清理逻辑。连接关闭时移除订阅、释放资源。区分正常关闭与异常断开,确保两种路径都执行清理。
心跳与重连
定期 ping/pong 检测半开连接,超时后终止并让客户端重连。客户端使用指数退避加抖动重连,恢复后重新认证并补拉错过的状态。服务端应支持幂等的订阅恢复。
背压与消息
慢客户端会导致发送缓冲区增长。监控 bufferedAmount,超过阈值时丢弃可丢消息、合并更新或断开连接。为消息定义版本和类型,限制单条大小,避免无界广播。
扩展与安全
多实例之间用 Redis Pub/Sub 或消息总线扇出,确保同一房间的消息到达所有节点。认证在握手时完成,授权在每个敏感操作上检查;限制每用户连接数和消息速率。
结论
实时功能的难点在失败路径。把心跳、重连、背压和跨实例分发当作核心需求,而不是上线后的补丁。
代码示例
// Server (ws): authenticate on upgrade, track connections per user.
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ noServer: true });
const connections = new Map<string, Set<WebSocket>>(); // userId -> sockets
server.on("upgrade", (req, socket, head) => {
const user = authenticate(req); // verify token/cookie from the upgrade request
if (!user) { socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n"); socket.destroy(); return; }
wss.handleUpgrade(req, socket, head, (ws) => {
const set = connections.get(user.id) ?? new Set();
set.add(ws); connections.set(user.id, set);
ws.on("close", () => { set.delete(ws); if (set.size === 0) connections.delete(user.id); });
ws.on("message", (data) => handleClientMessage(user.id, data));
});
});
function sendToUser(userId: string, message: object) {
for (const ws of connections.get(userId) ?? []) ws.send(JSON.stringify(message));
}
function startHeartbeat(ws: WebSocket, intervalMs = 30_000, timeoutMs = 10_000) {
let alive = true;
ws.on("pong", () => { alive = true; });
const timer = setInterval(() => {
if (!alive) return ws.terminate(); // missed two pings -> force close
alive = false;
ws.ping();
}, intervalMs);
ws.on("close", () => clearInterval(timer));
}
class RealtimeClient {
private ws?: WebSocket;
private reconnectDelay = 1000;
connect(url: string) {
this.ws = new WebSocket(url);
this.ws.onopen = () => { this.reconnectDelay = 1000; this.resubscribe(); };
this.ws.onmessage = (e) => this.handle(JSON.parse(e.data));
this.ws.onclose = () => this.scheduleReconnect(url);
this.ws.onerror = () => this.ws?.close();
}
private scheduleReconnect(url: string) {
const delay = Math.min(30_000, this.reconnectDelay) * (0.5 + Math.random());
this.reconnectDelay *= 2;
setTimeout(() => this.connect(url), delay);
}
private resubscribe() { for (const ch of this.subscriptions) this.send({ type: "subscribe", channel: ch }); }
}
function sendWithBackpressure(ws: WebSocket, data: string, maxBuffered = 1_000_000) {
if (ws.bufferedAmount > maxBuffered) {
// Consumer is slow; drop, sample, or wait. Never queue unboundedly.
return false;
}
ws.send(data);
return true;
}
// Each server subscribes to user topics and delivers to local connections.
await redis.subscribe("user:42");
redis.on("message", (channel, message) => {
const userId = channel.split(":")[1];
for (const ws of connections.get(userId) ?? []) ws.send(message);
});
// To send to a user from any server, publish to their topic.
async function notifyUser(userId: string, payload: object) {
await redis.publish(`user:${userId}`, JSON.stringify(payload));
}
ws.on("message", async (data) => {
const msg = JSON.parse(data.toString());
// Re-check authorization on every message with current permissions.
const allowed = await can(user.id, msg.action, msg.resource);
if (!allowed) { ws.send(JSON.stringify({ type: "error", code: "forbidden" })); return; }
handle(user.id, msg);
});
// Assign a server-side sequence number to each message in a room.
async function broadcast(roomId: string, message: object) {
const seq = await redis.incr(`room:${roomId}:seq`); // atomic counter
const envelope = { ...message, seq, at: Date.now() };
await redis.publish(`room:${roomId}`, JSON.stringify(envelope));
}
// Client orders by seq; displays gaps as "loading earlier messages".