let socket = null;
let heartbeatTimer = null;
let reconnectTimer = null;
// 定义重连函数
function reconnect() {
clearTimeout(reconnectTimer);
reconnectTimer = setTimeout(() => {
socket = new WebSocket('ws://url');
}, 3000);
}
// 发送心跳数据
function sendHeartbeat() {
clearTimeout(heartbeatTimer);
heartbeatTimer = setTimeout(() => {
socket.send('heartbeat');
}, 5000);
}
// 建立WebSocket连接
socket = new WebSocket('ws://url');
// 连接成功回调
socket.onopen = function() {
console.log('WebSocket连接成功');
// 首次连接成功后发送心跳数据
sendHeartbeat();
}
// 收到消息回调
socket.onmessage = function(e) {
console.log('收到消息:', e.data);
// 如果收到心跳数据,则再发送心跳数据
if (e.data === 'heartbeat') {
sendHeartbeat();
}
}
// socket关闭回调
socket.onclose = function() {
console.log('WebSocket断开连接');
// 启动重连定时器
reconnect();
}
// 发生错误回调
socket.onerror = function(e) {
console.log('WebSocket错误:', e);
}
// 启动心跳检测定时器
heartbeatTimer = setInterval(() => {
// 判断socket状态,关闭或已关闭则重连
if (!socket || socket.readyState == WebSocket.CLOSED) {
reconnect();
} else {
// 发送心跳数据
sendHeartbeat();
}
}, 5000);
标签:function,WebSocket,socket,sendHeartbeat,多次,heartbeatTimer,心跳,websocket,连接
From: https://www.cnblogs.com/chenkg/p/17728100.html