最近vue项目要做数据实时刷新,当用户用手机或者在后台取号结束,投屏需要做到实时刷新。
- 首先我们在页面刚进去的时候开始长连接,页面销毁时关闭长连接
data(){
return{
websock: null,
lockReconnect:false, //避免重复连接,因为onerror之后会立即触发 onclose
heartBeat:false,//心跳检测
}
},
created(){
//页面刚进入时开启长连接
this.initWebSocket()
},
destroyed: function() {
//页面销毁时关闭长连接
this.websock.close('4100') //离开路由之后断开websocket连接
clearTimeout(this.heartBeat.timeoutObj);
clearTimeout(this.heartBeat.serverTimeoutObj);
},
- 初始化webskoket
initWebSocket(){
let baseurl=this.accountinfo.base_ws_url
let wsurl = baseurl+'/hos?app_key=' + this.app_id;
this.websock = new WebSocket(wsurl);
this.websock.onopen = this.websocketonopen; //连接成功
this.websock.onmessage = this.websocketonmessage; //广播成功
this.websock.onerror = this.websocketonerror; //连接断开,失败
this.websock.onclose = this.websocketclose; //连接关闭
},
- 失败重连
websocketonerror(){
console.log('连接失败')
this.reconnect();
},
websocketclose(event){
//如果是主动关闭,不再重连
console.log('断开连接');
if(event.code=='4100'){
return;
}
this.reconnect();
},
reconnect(){
var that = this;
if(this.lockReconnect){//连接失败之后之后会相继触发 连接关闭,不然会连接上两个 WebSocket
return
}
this.lockReconnect = true;
setTimeout(()=>{ //没连接上会一直重连,设置延迟避免请求过多
console.log('失败重连')
that.msg="正在重连中"
that.fail_box=true;
that.initWebSocket();
that.lockReconnect = false;
},2000)
},
}
- 心跳检测
created(){
this.initWebSocket();
var that = this;
this.heartBeat = {
timeout: 5000,//10s
timeoutObj: null,
serverTimeoutObj: null,
heartStr:'1',
reset: function(){
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
this.start();
},
start: function(){
var self = this;
this.timeoutObj = setTimeout(function(){
that.websock.send(self.heartStr);
self.serverTimeoutObj = setTimeout(function(){
that.websock.close('4100');//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout)
}, this.timeout)
},
}
}
- 连接成功,监测心跳检测
websocketonopen(){
console.log('连接成功')
this.heartBeat.start();
},
*监听返回的信息
websocketonmessage(data){
this.heartBeat.reset();
console.log(data.data)//返回的信息
}
网友评论