data(){
return{
ipUrl: 'wss://www.findoma.com/handle-api',
// ipUrl: 'ws://192.168.100.233:8080',
ws: null,//建立的连接
lockReconnect: false,//是否真正建立连接
timeout: 28*1000,//30秒一次心跳
timeoutObj: null,//心跳心跳倒计时
serverTimeoutObj: null,//心跳倒计时
timeoutnum: null,//断开 重连倒计时
}
},
created(){
this.initWebpack();
},
methods: {
initWebpack(){
console.log('websocket初始化');
this.ws = new WebSocket(this.ipUrl + "/webSocket/" + this.createUser.userId); // 此处配置websocket地址
this.ws.onopen = this.onopen;
this.ws.onmessage = this.onmessage;
this.ws.onclose = this.onclose;
this.ws.onerror = this.onerror;
},
reconnect() {//重新连接
let that = this;
if(that.lockReconnect) {
return;
}
that.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
that.timeoutnum && clearTimeout(that.timeoutnum);
that.timeoutnum = setTimeout( () => {
//新连接
that.initWebpack();
that.lockReconnect = false;
},5000);
},
reset(){//重置心跳
let that = this;
//清除时间
clearTimeout(that.timeoutObj);
clearTimeout(that.serverTimeoutObj);
//重启心跳
that.start();
},
start(){//开启心跳
var self = this;
self.timeoutObj && clearTimeout(self.timeoutObj);
self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
self.timeoutObj = setTimeout(() => {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
if (self.ws.readyState == 1) {//如果连接正常
self.ws.send("heartCheck");
}else{//否则重连
self.reconnect();
}
self.serverTimeoutObj = setTimeout(function() {
//超时关闭
self.ws.close();
}, self.timeout);
}, self.timeout)
},
onopen() {
// 一下传参根据自己的实际项目(Cookies获取token)
let msg = JSON.stringify({cmd: 'enter_chatting', token:Cookies.get('Admin-Token')});
this.ws.send(1);
//开启心跳
this.start();
},
onmessage(e) {
console.log(e, '心跳机制返回');
// 在此处进行返回的信息处理
// 收到服务器信息,心跳重置
this.reset();
},
onclose(e) {
console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
let msg = JSON.stringify({cmd: 'out_chatting', token:Cookies.get('Admin-Token')});
this.ws.send(msg);
//重连
this.reconnect();
},
onerror(e) {
//重连
this.reconnect();
}
}
vue项目websocket及心跳机制
最新推荐文章于 2024-08-23 14:07:14 发布
这篇博客详细介绍了WebSocket的初始化、心跳机制、断开重连的实现过程。在创建WebSocket连接时,设置了心跳定时器以保持连接活跃,并在连接断开时自动尝试重新连接。同时,代码展示了如何处理服务器响应和错误情况,确保了服务的稳定性和可靠性。
摘要由CSDN通过智能技术生成