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

WebSocket在长时间通信中容易因网络波动或服务端超时导致连接中断。为了确保连接稳定,通常需要实现心跳检测与断线重连机制。下面介绍一种简单有效的实现方式。
心跳检测通过定时发送消息确认连接是否正常。客户端和服务端约定一个心跳消息格式,定期互发ping/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);
}
};
<p>function connect() {
ws = new WebSocket('ws://localhost:8080');</p><p>ws.onopen = () => {
heartCheck.reset().start();
};</p><p>ws.onmessage = (e) => {
if (e.data === 'pong') {
heartCheck.reset().start(); // 收到pong,重启心跳
}
};
}
当连接关闭或心跳超时,自动尝试重新连接,避免频繁重试可设置最大重连次数和间隔时间。
实现要点:
// 示例:断线重连逻辑
let reconnectInterval = 1000;
let maxReconnectAttempts = 5;
let reconnectAttempts = 0;
<p>ws.onclose = () => {
if (reconnectAttempts < maxReconnectAttempts) {
setTimeout(() => {
reconnectAttempts++;
connect();
console.log(<code>第 ${reconnectAttempts} 次重连尝试</code>);
}, 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);
}
};
<p>let reconnectInterval = 1000;
let maxReconnectAttempts = 5;
let reconnectAttempts = 0;</p><p>function connect() {
ws = new WebSocket('ws://localhost:8080');</p><p>ws.onopen = () => {
reconnectAttempts = 0; // 成功连接,重置重连计数
heartCheck.reset().start();
};</p><p>ws.onmessage = (e) => {
if (e.data === 'pong') {
heartCheck.reset().start();
} else {
// 处理正常业务消息
console.log('收到消息:', e.data);
}
};</p><p>ws.onclose = () => {
heartCheck.reset(); // 清除心跳定时器
if (reconnectAttempts < maxReconnectAttempts) {
setTimeout(() => {
reconnectAttempts++;
connect();
}, reconnectInterval * Math.pow(2, reconnectAttempts));
}
};</p><p>ws.onerror = () => {
console.error('WebSocket错误');
};
}</p><p>// 初始化连接
connect();
基本上就这些。心跳加重连能显著提升WebSocket的稳定性,实际项目中可根据需求调整超时时间和重试策略。
以上就是WebSocket心跳检测与断线重连示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号