websocket 以及心跳檢測實現長連接


1:再data中定義

 

 

heartCheck: {
timeout: 6000,
timeoutObj: null,
serverTimeoutObj: null,
start: function (ws) {
var self = this
this.timeoutObj && clearTimeout(this.timeoutObj)
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
this.timeoutObj = setTimeout(function () {
// 這里發送一個心跳,后端收到后,返回一個心跳消息,
if (ws.readyState === 3) {
return
}
console.log('發送了心跳檢測')
ws.send('HeartBeat')
self.serverTimeoutObj = setTimeout(function () {
console.log('檢測不到心跳')
ws.close()
}, self.timeout)
}, this.timeout)
}
}
2:
再created中調用
this.initWebSocket()
initWebSocket () { // 初始化weosocket
this.destroyWebSocket()
try {
console.log('連接websocket')
const wsuri = 'ws://' + this.dataM.split('/')[2] + '?pageId=' + generateUUID()// ws地址
this.webSocket = new WebSocket(wsuri)
this.webSocket.onopen = (event) => {
console.log('send:' + this.currSceneInfo.id)
this.webSocket.send(this.currSceneInfo.id)
this.heartCheck.start(this.webSocket) // 心跳
}
this.webSocket.onmessage = (event) => {
if (event.data === 'HeartBeat') {
console.log('收到了心跳檢測')
this.heartCheck.start(this.webSocket) // 心跳
} else {
const data = JSON.parse(event.data)
 
 
}
}
this.webSocket.onerror = () => {
console.log('發生異常了')
this.reconnect() // 重連
}
this.webSocket.onclose = (event) => {
console.log('斷線重連')
this.reconnect() // 重連
}
} catch (e) {
console.log(e.message)
this.reconnect()
}
},

 

destroyWebSocket () {
if (this.webSocket) {
this.webSocket.onclose = (event) => {
console.log('鏈接關閉')
}
this.webSocket.close()
this.webSocket = null
}
},

 

 

 

destroyed () {
this.destroyWebSocket()
},
reconnect () {
if (this.lockReconnect) {
return
}

 

 

this.lockReconnect = true
// 沒連接上會一直重連,設置延遲避免請求過多
this.tt && clearTimeout(this.tt)
this.tt = setTimeout(() => {
this.initWebSocket()
this.lockReconnect = false
}, 4000)
},
 


免責聲明!

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



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