概述
WebSocket 连接在网络静默失败时会退化成“僵尸管道”:NAT 映射消失、负载均衡器回收空闲连接后,客户端仍在向无人接收的套接字写数据,可能数分钟后才被发现,期间用户界面完全冻结。可靠的长连接层需要三个机制叠加:带硬性截止时间的心跳负责快速检测、带抖动退避的自动重连负责恢复、基于序列号的状态同步保证恢复后数据正确。
核心机制
RFC 6455 的 ping/pong 是协议层控制帧,对应用处理器透明,是理想的存活探测通道。心跳间隔必须短于路径上最短的空闲超时(云负载均衡常为 60 秒,故 20-30 秒较稳妥),且必须配套截止时间:pong 未按时到达即判定连接死亡。重连退避必须加随机抖动,否则服务重启后成千上万客户端同步重试,瞬间重建故障。服务端 ping 需要独立写截止时间,防止半开连接的 TCP 发送缓冲阻塞心跳循环。
实现要点
浏览器端用看门狗模式:setTimeout(() => this.ws.close(), 45_000),任何入站流量(含 pong)都重置计时器。重连计算 delay = base * (0.5 + Math.random() * 0.5) 加入抖动。服务端 Go 实现:conn.SetPongHandler(...) 每次 pong 延长读截止时间,ping 定时器每 25 秒发送一次。每条消息携带单调递增序列号,重连时客户端上报 lastSeq,服务端小缺口重放缓冲区、大缺口发快照重置。
常见陷阱
常见陷阱:客户端无看门狗导致半开连接下界面静默冻结;仅依赖 TCP keepalive(内核默认间隔过长);固定重连延迟无抖动引发同步风暴;重连却不重同步,连接恢复但视图过期;重放缓冲无上限导致一小时流量回放挤占新消息;ping 写操作无截止时间被卡住的发送缓冲拖死心跳。
验证方式
所有故障路径都可通过注入测试:服务端杀连接断言客户端按退避窗口重连;冻结服务进程(不关套接字)断言看门狗在截止时间内触发,验证的是检测逻辑而非关闭处理;用假时钟确定性测试退避时序;断开期间投递消息后重连,验证重放与顺序保持;启动百个客户端杀掉再重启服务,断言重连到达在抖动窗口内分散而非单点尖峰。
代码示例
type Listener = (msg: { seq: number; kind: string; data: unknown }) => void;
export class ReconnectingSocket {
private ws: WebSocket | null = null;
private lastSeq = 0;
private attempt = 0;
private timer: number | undefined;
private watchdog: number | undefined;
constructor(private url: string, private onMessage: Listener) {}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onmessage = (e) => {
this.resetWatchdog();
const msg = JSON.parse(e.data as string);
this.lastSeq = msg.seq;
this.onMessage(msg);
};
this.ws.onopen = () => {
this.attempt = 0;
this.resetWatchdog();
this.send({ kind: 'resync', since: this.lastSeq });
};
this.ws.onclose = () => this.scheduleReconnect();
this.ws.onerror = () => this.ws?.close();
this.resetWatchdog();
}
private resetWatchdog() {
clearTimeout(this.watchdog);
this.watchdog = setTimeout(() => this.ws?.close(), 45_000);
}
private scheduleReconnect() {
clearTimeout(this.watchdog);
const base = Math.min(30_000, 500 * 2 ** this.attempt);
const delay = Math.round(base * (0.5 + Math.random() * 0.5));
this.attempt = Math.min(this.attempt + 1, 8);
this.timer = setTimeout(() => this.connect(), delay);
}
send(obj: object) { this.ws?.send(JSON.stringify(obj)); }
close() { clearTimeout(this.timer); clearTimeout(this.watchdog); this.ws?.close(); }
}
func readPump(conn *websocket.Conn, out chan<- inbound) {
conn.SetReadLimit(64 << 10)
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})
for {
_, msg, err := conn.ReadMessage()
if err != nil { close(out); return }
out <- parse(msg)
}
}
func pingPump(conn *websocket.Conn, done <-chan struct{}) {
ticker := time.NewTicker(25 * time.Second)
defer func() { ticker.Stop(); conn.Close() }()
for {
select {
case <-ticker.C:
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil { return }
case <-done:
return
}
}
}
const sock = new ReconnectingSocket(url, collector.push);
vi.useFakeTimers();
sock.connect();
server.dropConnection(1);
vi.advanceTimersByTime(500);
expect(sock.connected()).toBe(false);
vi.advanceTimersByTime(500);
expect(sock.connected()).toBe(true);
expect(collector.messagesFromSeq(0)).toHaveLength(3);