最近vue項(xiàng)目要做數(shù)據(jù)實(shí)時(shí)刷新苍苞,當(dāng)用戶用手機(jī)或者在后臺(tái)取號(hào)結(jié)束衔瓮,投屏需要做到實(shí)時(shí)刷新郊霎。
- 首先我們?cè)陧撁鎰傔M(jìn)去的時(shí)候開始長(zhǎng)連接钉汗,頁面銷毀時(shí)關(guān)閉長(zhǎng)連接
data(){
return{
websock: null,
lockReconnect:false, //避免重復(fù)連接姥饰,因?yàn)閛nerror之后會(huì)立即觸發(fā) onclose
heartBeat:false,//心跳檢測(cè)
}
},
created(){
//頁面剛進(jìn)入時(shí)開啟長(zhǎng)連接
this.initWebSocket()
},
destroyed: function() {
//頁面銷毀時(shí)關(guān)閉長(zhǎng)連接
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; //連接關(guān)閉
},
- 失敗重連
websocketonerror(){
console.log('連接失敗')
this.reconnect();
},
websocketclose(event){
//如果是主動(dòng)關(guān)閉,不再重連
console.log('斷開連接');
if(event.code=='4100'){
return;
}
this.reconnect();
},
reconnect(){
var that = this;
if(this.lockReconnect){//連接失敗之后之后會(huì)相繼觸發(fā) 連接關(guān)閉列粪,不然會(huì)連接上兩個(gè) WebSocket
return
}
this.lockReconnect = true;
setTimeout(()=>{ //沒連接上會(huì)一直重連审磁,設(shè)置延遲避免請(qǐng)求過多
console.log('失敗重連')
that.msg="正在重連中"
that.fail_box=true;
that.initWebSocket();
that.lockReconnect = false;
},2000)
},
}
- 心跳檢測(cè)
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會(huì)執(zhí)行reconnect,我們執(zhí)行ws.close()就行了.如果直接執(zhí)行reconnect 會(huì)觸發(fā)onclose導(dǎo)致重連兩次
}, self.timeout)
}, this.timeout)
},
}
}
- 連接成功岂座,監(jiān)測(cè)心跳檢測(cè)
websocketonopen(){
console.log('連接成功')
this.heartBeat.start();
},
*監(jiān)聽返回的信息
websocketonmessage(data){
this.heartBeat.reset();
console.log(data.data)//返回的信息
}