实时通信:WebSocket 重连、心跳与消息可靠
MrSmy Lv5

new WebSocket(url) 一行就能连上,但生产环境要考虑的远不止这个:网络切换、服务端重启、消息丢失、多标签页重复连接、代理超时断开。

这篇把这几个问题逐个拆开。

基础封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class RealtimeClient {
constructor(url, options = {}) {
this.url = url
this.handlers = new Set()
this.status = 'idle'
this.retryCount = 0
this.maxRetry = options.maxRetry ?? 10
this.queue = [] // 断线期间待发送的消息
this.lastSeq = 0 // 已收到的最大序号
}

connect() {
if (this.status === 'connecting' || this.status === 'open') return

this.status = 'connecting'
this.ws = new WebSocket(this.url)

this.ws.onopen = () => {
this.status = 'open'
this.retryCount = 0
this.startHeartbeat()
this.flush()
this.emit({ type: 'open' })
}

this.ws.onmessage = (e) => {
const msg = JSON.parse(e.data)
if (msg.type === 'pong') {
this.lastPongAt = Date.now()
return
}
if (typeof msg.seq === 'number') {
if (msg.seq <= this.lastSeq) return // 重复消息,丢弃
this.lastSeq = msg.seq
}
this.emit(msg)
}

this.ws.onclose = (e) => {
this.status = 'closed'
this.stopHeartbeat()
this.emit({ type: 'close', code: e.code, reason: e.reason })
if (!e.wasClean || e.code !== 1000) {
this.scheduleReconnect()
}
}

this.ws.onerror = () => {
// onerror 之后一定会有 onclose,不要在这里重连
this.emit({ type: 'error' })
}
}

on(handler) {
this.handlers.add(handler)
return () => this.handlers.delete(handler)
}

emit(event) {
this.handlers.forEach((h) => h(event))
}

send(msg) {
const payload = JSON.stringify(msg)
if (this.status === 'open') {
this.ws.send(payload)
} else {
this.queue.push(payload) // 断线时排队
}
}

flush() {
while (this.queue.length && this.status === 'open') {
this.ws.send(this.queue.shift())
}
}
}

重连:指数退避 + 抖动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
scheduleReconnect() {
if (this.retryCount >= this.maxRetry) {
this.emit({ type: 'giveup' })
return
}

// 1s, 2s, 4s, 8s, 16s, 30s(封顶)
const base = Math.min(1000 * 2 ** this.retryCount, 30000)
// 加抖动,避免服务端恢复时所有客户端同时重连(惊群)
const delay = base * (0.5 + Math.random() * 0.5)

this.retryCount++
this.retryTimer = setTimeout(() => this.connect(), delay)
this.emit({ type: 'reconnecting', attempt: this.retryCount, delay })
}

为什么必须加抖动:服务端重启时 10000 个客户端会在同一秒内全部重连,直接把刚起来的服务再打挂。加 ±50% 的随机后,重连请求会分散在几秒内。

为什么要封顶:用户挂机一晚上,2^30 秒的重连间隔毫无意义。封顶 30 秒并在页面可见时才重连。

1
2
3
4
5
6
7
8
// 页面隐藏时暂停重连
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
client.pauseReconnect()
} else {
client.resumeReconnect() // 立即试一次
}
})

为什么要监听 online 事件:

1
2
3
4
5
6
window.addEventListener('online', () => {
if (client.status === 'closed') {
client.retryCount = 0 // 网络恢复了,重置重试计数
client.connect()
}
})

心跳:解决”假死连接”

TCP 连接可能处于”半开”状态:网络断了,但客户端毫不知情(没有收到 FIN)。表现是以为还连着,实际发不出去也收不到。

代理(Nginx、负载均衡)通常有 60 秒空闲超时,超时会直接断开而不通知。

心跳两个方向都要有:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
startHeartbeat() {
this.lastPongAt = Date.now()

this.pingTimer = setInterval(() => {
// 超过 2 个周期没收到 pong → 判定死了
if (Date.now() - this.lastPongAt > 45000) {
this.ws.close(4000, 'heartbeat timeout')
return
}
this.ws.send(JSON.stringify({ type: 'ping', t: Date.now() }))
}, 20000)
}

stopHeartbeat() {
clearInterval(this.pingTimer)
this.pingTimer = null
}

服务端也要回 pong,并且服务端自己也要主动探测(双向):

1
2
3
4
5
6
7
8
9
10
// Node 服务端
setInterval(() => {
for (const client of clients) {
if (Date.now() - client.lastSeenAt > 60000) {
client.ws.terminate()
continue
}
client.ws.ping() // ws 库的协议级 ping
}
}, 30000)

协议级 ping/pong 更省事:WebSocket 协议本身支持 ping/pong 帧,ws 库会自动回 pong。但问题是浏览器的 WebSocket API 不暴露 ping/pong——前端无法主动发协议级 ping。

所以前端只能用”业务层心跳”(发一个 JSON 消息),或者干脆”服务端 ping + 前端检测 pong 不了”(前端也看不到 pong 帧)。

实际的方案:

  • 前端发业务 ping,服务端回业务 pong(最常见)
  • 服务端可以额外用协议级 ping 做探测(对 Node 服务端有效)

间隔怎么定:心跳间隔要小于代理的空闲超时。Nginx 默认 proxy_read_timeout 60s,所以心跳间隔用 20-30 秒。

消息可靠性

WebSocket 保证”在连接存活期间,消息按序到达”(TCP 特性)。但不保证”跨连接”的可靠性:

1
2
3
连接 1:收到 seq 1,2,3
[断线]
连接 2:收到 seq 7,8,9 ← 4,5,6 丢了

三件事要做:

1. 消息序号 + 去重

1
2
3
4
5
6
7
8
9
onmessage: (msg) => {
if (msg.seq <= this.lastSeq) return // 重复(服务端重发)
if (msg.seq > this.lastSeq + 1) {
// 有缺口,主动拉取
this.requestCatchup(this.lastSeq + 1, msg.seq - 1)
}
this.lastSeq = msg.seq
this.emit(msg)
}

2. 重连后补齐

连接时带上”我已经收到的最大序号”:

1
2
3
4
5
connect() {
const url = new URL(this.url)
url.searchParams.set('since', this.lastSeq)
this.ws = new WebSocket(url)
}

服务端从序号之后的消息开始补发(需要服务端有消息存储,比如 Redis Stream / Kafka)。

1
2
3
4
5
6
7
8
9
// 服务端
ws.on('connection', (socket, req) => {
const since = Number(new URL(req.url, 'http://x').searchParams.get('since') || 0)
if (since > 0) {
const missed = await store.getMessagesAfter(channel, since, 1000)
for (const msg of missed) socket.send(JSON.stringify(msg))
}
subscribe(socket, channel)
})

3. 上行消息的 ACK

客户端的 send 不代表”服务端收到了”。要 ACK:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const pending = new Map()      // clientMsgId → { payload, timer }

send(msg) {
const id = crypto.randomUUID()
const envelope = { ...msg, clientMsgId: id }
this.ws.send(JSON.stringify(envelope))

const timer = setTimeout(() => retry(id), 5000)
pending.set(id, { envelope, timer })
}

// 收到 ack
onAck(clientMsgId) {
const item = pending.get(clientMsgId)
if (item) {
clearTimeout(item.timer)
pending.delete(clientMsgId)
}
}

服务端需要对客户端消息做幂等处理(同一个 clientMsgId 只处理一次)。

多标签页问题

用户开了 5 个标签页,就建立了 5 条 WebSocket 连接。问题:

  • 服务端连接数 ×5
  • 消息被处理 5 次(比如”新消息提示音”响 5 遍)
  • 状态不同步

三种方案:

1. Leader Election(推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 用 BroadcastChannel + localStorage 选出唯一连接者
const bc = new BroadcastChannel('realtime')
const TAB_ID = crypto.randomUUID()

function electLeader() {
const leader = localStorage.getItem('realtime:leader')
const heartbeat = Number(localStorage.getItem('realtime:leaderAt') || 0)

// 没 leader 或 leader 心跳过期 → 竞选
if (!leader || Date.now() - heartbeat > 5000) {
localStorage.setItem('realtime:leader', TAB_ID)
localStorage.setItem('realtime:leaderAt', String(Date.now()))
bc.postMessage({ type: 'leader', id: TAB_ID })
return true
}
return leader === TAB_ID
}

Leader 负责建连,收到消息后通过 BroadcastChannel 转发给其他标签页:

1
2
3
4
5
6
7
8
9
10
11
// leader
ws.onmessage = (e) => {
const msg = JSON.parse(e.data)
this.handle(msg)
bc.postMessage({ type: 'message', data: msg }) // 广播
}

// follower
bc.onmessage = (e) => {
if (e.data.type === 'message') this.handle(e.data.data)
}

2. SharedWorker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// shared-worker.js
const clients = new Set()
let ws

self.onconnect = (e) => {
const port = e.ports[0]
clients.add(port)

if (!ws) {
ws = new WebSocket('/ws')
ws.onmessage = (ev) => {
clients.forEach((p) => p.postMessage(ev.data))
}
}

port.onmessage = (ev) => {
if (ws.readyState === WebSocket.OPEN) ws.send(ev.data)
}

port.start()
}

SharedWorker 全局只有一个实例,天然解决多连接问题。但 Safari 直到最近才支持(Safari 16+ 才有),测试环境也要注意。

3. Service Worker 保持连接

理论上可以,但 SW 会被浏览器休眠,不适合长连接。

我们的选择:BroadcastChannel + localStorage leader 选举。兼容性好(BroadcastChannel 在 2020 年后所有主流浏览器都支持),实现不复杂。

SSE 还是 WebSocket

WebSocket SSE(EventSource)
方向 双向 单向(服务端 → 客户端)
协议 ws:// HTTP
自动重连 要自己实现 内置
断点续传 要自己实现 内置(Last-Event-ID)
二进制 支持 只能文本(base64)
HTTP/2 不支持(要单独连接) 可以复用
代理/防火墙 有时被拦 就是 HTTP,最兼容
无需上行时 过度设计 更合适

什么时候 SSE 更好:

  • 只需要”服务端推 → 客户端”(通知、进度条、日志流、AI 流式输出)
  • 需要简单(EventSource 几行就用)
  • 需要穿越严格的企业代理
1
2
3
4
// SSE 用法
const es = new EventSource('/api/stream')
es.onmessage = (e) => handle(e.data)
es.onerror = () => { /* 浏览器会自动重连 */ }

EventSource 的自动重连和 Last-Event-ID 是免费得到的——服务端只要在消息里写 id: 123,重连时浏览器自动带上 Last-Event-ID: 123。

但 SSE 的局限:浏览器限制同域最多 6 个并发 HTTP 连接(HTTP/1.1),SSE 会占用其中一个。HTTP/2 下没有这个问题。

我们的实践:AI 流式输出、任务进度、通知推送用 SSE;需要双向的协作编辑、即时聊天用 WebSocket。

服务端的几个关键点

1. 连接数上限

1
2
// Node 默认的 fd 限制
ulimit -n 65535

单机 10000 连接时,内存占用约 500MB-1GB(每连接有收发缓冲)。要调:

1
2
3
4
5
const wss = new WebSocketServer({
server,
maxPayload: 1024 * 1024, // 限制单条消息 1MB,防打爆内存
perMessageDeflate: false, // 压缩会增加 CPU(通常关掉)
})

2. 优雅关闭

1
2
3
4
5
6
7
process.on('SIGTERM', () => {
wss.clients.forEach((ws) => {
ws.send(JSON.stringify({ type: 'shutdown' })) // 通知客户端
ws.close(1001, 'server shutdown') // 1001 = going away
})
setTimeout(() => process.exit(0), 3000)
})

客户端收到 1001 时应该快速重连(不带退避),因为这是计划内的重启。

1
2
3
4
5
6
7
8
9
onclose: (e) => {
if (e.code === 1001) {
// 服务端主动关闭,立即重连
this.retryCount = 0
setTimeout(() => this.connect(), 1000)
} else {
this.scheduleReconnect()
}
}

3. 集群下的广播

单机可以用内存维护订阅关系,多实例就必须用 Redis Pub/Sub 或专门的网关:

1
2
3
4
5
6
7
// 每个实例都订阅 Redis 频道
subscriber.subscribe('broadcast:room:123')
subscriber.on('message', (channel, message) => {
// 转发给本实例上订阅了该房间的客户端
const clients = rooms.get('123') ?? []
clients.forEach((ws) => ws.send(message))
})

规模再大就要用专门的方案(Centrifugo、Socket.IO 的 Redis adapter、NATS)。

踩过的坑

1. onerror 之后立即重连

onerror 一定跟着 onclose,在 onerror 里重连会导致双倍连接。只在 onclose 里重连。

2. 1006 错误码

1
CloseEvent { code: 1006, reason: '', wasClean: false }

1006 是”异常关闭,没有收到关闭帧”——通常就是网络断了。它不能在代码里主动构造(不能 close(1006)),只能被动收到。

3. Nginx 配置漏了 Upgrade 头

1
2
3
4
5
6
7
8
location /ws {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 3600s; # 长连接要调大
proxy_send_timeout 3600s;
}

漏了 Upgrade 和 Connection 头,握手会失败(返回 400 或 426)。这个是自建部署最常见的错误。

4. 消息太大被截断

maxPayload 默认值是 100MB(ws 库),但某些网关有限制。发 1MB 以上的 JSON 要考虑分片。

5. 重连时重复订阅

1
2
3
4
// ❌ 每次重连都订阅,服务端重复推送
ws.onopen = () => {
ws.send(JSON.stringify({ type: 'subscribe', room: 'chat' }))
}

服务端要按连接维度去重(同一个连接对同一个房间只保留一个订阅),或者前端在 onopen 里先发 unsubscribe 再 subscribe。

6. 心跳和重连的定时器泄漏

组件卸载后定时器还在跑,不停尝试重连(并且持有整个组件闭包)。必须在 destroy() 里清理:

1
2
3
4
5
6
destroy() {
clearInterval(this.pingTimer)
clearTimeout(this.retryTimer)
this.ws?.close(1000, 'client destroy')
this.handlers.clear()
}

7. send 在 CONNECTING 状态抛异常

1
2
3
4
5
6
// ❌ 会抛错
ws.send(data) // InvalidStateError

// ✅ 检查状态或排队
if (ws.readyState === WebSocket.OPEN) ws.send(data)
else queue.push(data)

一份状态可视化

用户需要知道”现在是连着还是断着”。UI 上的四种状态:

状态 提示 允许操作
connecting “连接中…” 只读
open 绿色圆点 / 无提示 全部
reconnecting “连接断开,正在重连(第 3 次)” 只读 + 本地草稿
giveup “连接失败,请刷新页面” 手动重试按钮

**”只读 + 本地草稿”**这点很重要:断线时用户不该被”你的操作失败了”打断,应该允许继续输入,等恢复后再发。这需要本地持久化(localStorage 或 IndexedDB)配合队列。

小结

可用的实时通信需要四件事:

能力 关键实现
能连上 指数退避 + 抖动 + online 事件
知道断了 双向心跳 + 超时判定
不丢消息 序号 + 去重 + 重连补齐 + 上行 ACK
不多连 Leader 选举 / SharedWorker

判断”要不要 WebSocket”:

  • 只需下行 → SSE(更简单,自带重连和断点续传)
  • 需要双向 → WebSocket
  • 只需低频轮询 → 普通 HTTP + 长轮询

最后一点体会:实时功能的复杂度 80% 在”异常路径”上。正常网络下的连通只占 20%,剩下的是弱网、切换网络、服务端重启、多标签页。这些场景在开发环境几乎测不出来,必须在真机上验证(尤其是移动端切 Wi-Fi/4G)。

  • 本文标题:实时通信:WebSocket 重连、心跳与消息可靠
  • 本文作者:MrSmy
  • 创建时间:2026-01-11 20:24:00
  • 本文链接:https://fengyang.live/2026/01/11/实时通信:WebSocket重连、心跳与消息可靠/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!