websocket实现心跳连接

在使用websocket的时候,遇到了一个websocket在连接一段时间就异常断开连接了。第一想法就是重新去连接websocket(websock.onopen),后来发现这种方式是错误的,查阅文档发现,要想重新建立连接,就需要一种心跳思想去处理(实时监听连接情况,断了就去重连)
下面以Vue代码为准:


let lockReconnect = false;//避免重复连接
let wsUrl = '‘ // url;
let ws;
let tt;


createWebSocket() {
let that = this;
try {
ws = new WebSocket(wsUrl);
this.init();
} catch(e) {
console.log('catch');
that.reconnect(wsUrl);
}
},
init() {
let that = this;

//心跳检测
let heartCheck = {
timeout: 3000,
timeoutObj: null,
serverTimeoutObj: null,
start: function(){
console.log('start');
let self = this;
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
console.log('55555');
ws.send("888");
self.serverTimeoutObj = setTimeout(function() {
console.log(111);
console.log(ws);
ws.close();
// createWebSocket();
}, self.timeout);

}, this.timeout)
}
};
ws.onclose = function () {
console.log('链接关闭');
that.reconnect(wsUrl);
location.reload()
};
ws.onerror = function() {
console.log('发生异常了');
that.reconnect(wsUrl);
location.reload();
};
ws.onopen = function () {
//心跳检测重置
heartCheck.start();
};
ws.onmessage = function (e) {
//拿到任何消息都说明当前连接是正常的
console.log('接收到消息');
console.log(e);

heartCheck.start();
}
},
reconnect(url) {
if(lockReconnect) {
return;
}
lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
tt && clearTimeout(tt);
tt = setTimeout( () => {
this.createWebSocket(url);
lockReconnect = false;
}, 4000);
},

 

this.createWebSocket(wsUrl);

转载于:https://www.cnblogs.com/exmyth/p/11588696.html

### 如何在 WebSocket实现心跳机制 为了确保 WebSocket 连接的稳定性和实时性,通常会引入心跳机制。该机制能够定期发送消息以确认连接状态,防止因长时间无通信而导致断开。 #### 创建 WebSocket 实例并初始化事件处理程序 首先需要创建 WebSocket 实例并与服务器建立连接: ```javascript function createWebSocket(url) { const ws = new WebSocket(url); function initEventHandle() { ws.onopen = () => console.log('Connection opened'); ws.onerror = (error) => console.error(`Error occurred: ${error}`); ws.onmessage = (event) => handleMessage(event.data); ws.onclose = () => handleDisconnect(); } initEventHandle(); return ws; } ``` #### 定义心跳检测逻辑 定义一个定时器用于周期性地向服务器发送心跳包,并监听来自服务器的心跳响应: ```javascript let heartbeatInterval; function startHeartbeat(wsInstance, intervalSeconds=30){ clearInterval(heartbeatInterval); // 清除之前的计时器 heartbeatInterval = setInterval(() => { try{ wsInstance.send(JSON.stringify({ type:"ping"})); console.log("Sent ping to server"); setTimeout(()=>{ if(!wsInstance.readyState === WebSocket.OPEN){ console.warn("No pong received from server within timeout period."); wsInstance.close(); } },intervalSeconds*1000/2); // 设置超时时间 }catch(error){ console.error("Failed sending ping:", error.message); } }, intervalSeconds * 1000); } // 处理收到的消息,当收到pong回应时重置关闭判定 function handleMessage(messageData){ let messageObj = JSON.parse(messageData); switch(messageObj.type){ case 'pong': console.info("Received pong response from server"); break; default: // Handle other types of messages here... break; } } ``` 上述代码展示了如何设置每 `intervalSeconds` 秒一次的心跳探测过程[^2]。如果超过一半的时间间隔还没有收到来自服务器的回复,则认为连接可能已经失效而尝试重新连接或执行其他恢复操作。 #### 关闭连接后的处理 当 WebSocket 断开时应停止心跳检测循环,并可选择自动重连或其他措施: ```javascript function handleDisconnect(){ clearInterval(heartbeatInterval); console.log('Disconnected from the server.'); // 可选:在此处加入重试逻辑 } ``` 通过这种方式可以有效地维持 WebSocket 长期稳定的双向通信通道[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值