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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM