WebSocket通过心跳检测与断线重连机制提升连接稳定性,客户端每30秒发送ping,服务端回应pong,超时未响应则判定断线;onclose触发后按指数退避策略重试连接,最多5次,确保网络波动后可靠恢复。

WebSocket在长时间通信中容易因网络波动或服务端超时导致连接中断。为了确保连接稳定,通常需要实现心跳检测与断线重连机制。下面介绍一种简单有效的实现方式。
心跳检测机制
心跳检测通过定时发送消息确认连接是否正常。客户端和服务端约定一个心跳消息格式,定期互发ping/pong消息。
关键点:
- 设置定时器,每隔一定时间(如30秒)向服务端发送ping消息
- 服务端收到ping后应答pong
- 客户端记录最后一次收到pong的时间,超时未响应则判定为断线
// 示例:客户端心跳逻辑
let ws;
let heartCheck = {
timeout: 30000,
timer: null,
reset: function() {
clearTimeout(this.timer);
return this;
},
start: function() {
this.timer = setInterval(() => {
ws.send('ping');
}, this.timeout);
}
};
function connect() {
ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
heartCheck.reset().start();
};
ws.onmessage = (e) => {
if (e.data === 'pong') {
heartCheck.reset().start(); // 收到pong,重启心跳
}
};
}
断线重连机制
当连接关闭或心跳超时,自动尝试重新连接,避免频繁重试可设置最大重连次数和间隔时间。
实现要点:
- 监听onclose事件触发重连
- 设置重连次数限制,防止无限重试
- 使用指数退避策略增加重连间隔
// 示例:断线重连逻辑
let reconnectInterval = 1000; let maxReconnectAttempts = 5; let reconnectAttempts = 0;ws.onclose = () => { if (reconnectAttempts < maxReconnectAttempts) { setTimeout(() => { reconnectAttempts++; connect(); console.log(
第 ${reconnectAttempts} 次重连尝试); }, reconnectInterval * Math.pow(2, reconnectAttempts)); } else { console.warn('重连次数已达上限'); } };
完整示例整合
将心跳与重连结合,形成健壮的WebSocket连接管理。
let ws;
let heartCheck = {
timeout: 30000,
timer: null,
reset: function() {
clearTimeout(this.timer);
return this;
},
start: function() {
this.timer = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send('ping');
}
}, this.timeout);
}
};
let reconnectInterval = 1000;
let maxReconnectAttempts = 5;
let reconnectAttempts = 0;
function connect() {
ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
reconnectAttempts = 0; // 成功连接,重置重连计数
heartCheck.reset().start();
};
ws.onmessage = (e) => {
if (e.data === 'pong') {
heartCheck.reset().start();
} else {
// 处理正常业务消息
console.log('收到消息:', e.data);
}
};
ws.onclose = () => {
heartCheck.reset(); // 清除心跳定时器
if (reconnectAttempts < maxReconnectAttempts) {
setTimeout(() => {
reconnectAttempts++;
connect();
}, reconnectInterval * Math.pow(2, reconnectAttempts));
}
};
ws.onerror = () => {
console.error('WebSocket错误');
};
}
// 初始化连接
connect();
基本上就这些。心跳加重连能显著提升WebSocket的稳定性,实际项目中可根据需求调整超时时间和重试策略。









