【笔记】vue中websocket⼼跳机制data () {
return {
ws: null,//建⽴的连接
lockReconnect: false,//是否真正建⽴连接
timeout: 28*1000,//30秒⼀次⼼跳
timeoutObj: null,//⼼跳⼼跳倒计时
serverTimeoutObj: null,//⼼跳倒计时
timeoutnum: null,//断开重连倒计时
}
},
created() {
this.initWebpack();
},
methods: {
initWebpack(){
this.ws = new v.SOCKET_OTC);
pen = pen;
ssage = ssage;
lose = lose;
r = r;
},
reconnect() {//重新连接
var that = this;
if(that.lockReconnect) {websocket和socket
return;
};
that.lockReconnect = true;
//没连接上会⼀直重连,设置延迟避免请求过多
that.timeoutnum && clearTimeout(that.timeoutnum);
that.timeoutnum = setTimeout(function () {
//新连接
that.initWebpack();
that.lockReconnect = false;
},5000);
},
reset(){//重置⼼跳
var 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(function(){
//这⾥发送⼀个⼼跳,后端收到后,返回⼀个⼼跳消息,
if (adyState == 1) {//如果连接正常
self.ws.send("heartCheck");
}else{//否则重连
}
self.serverTimeoutObj = setTimeout(function() {
/
/超时关闭
self.ws.close();
}, self.timeout);
}, self.timeout)
},
onopen() {
var msg = JSON.stringify({cmd: 'enter_chatting', token:Cookie("token")});
this.ws.send(msg);
console.log("open");
//开启⼼跳
this.start();
},
onmessage(e) {
data.fromID == this.states.customerId){
}else{
}
var content =data.chatType);
/
/收到服务器信息,⼼跳重置
},
onclose(e) {
console.log("连接关闭");
console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
var msg = JSON.stringify({cmd: 'out_chatting', token:Cookie("token")}); this.ws.send(msg);
//重连
},
onerror(e) {
console.log("出现错误");
//重连
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论