日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

websocket 以及心跳检测实现长连接

發布時間:2023/12/31 综合教程 24 生活家
生活随笔 收集整理的這篇文章主要介紹了 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)
},

總結

以上是生活随笔為你收集整理的websocket 以及心跳检测实现长连接的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。