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)
},
 

posted on 2019-10-25 10:44  冰love  阅读(4586)  评论(0编辑  收藏  举报

导航