Vue使用websocket进行心跳连接
Vue页面template<template><div><canvas style="width: 80%!important;height: auto!important;" id="canvas"></canvas><br/>{{charId}}</div></template>Vue页面js<scrip
·
Vue页面js
export default {
name: 'EnterMeeting',
data() {
return {
ws: null,
isDestroyed: false, // 页面是否销毁
lockReconnect: false, // 是否真正建立连接
timeout: 20000, // 20秒一次心跳
timeoutObj: null, // 心跳心跳倒计时
serverTimeoutObj: null, // 心跳倒计时
timeoutnum: null, // 断开 重连倒计时
}
},
mounted() {
// 初始化websocket
this.initWebSocket()
},
// 页面销毁
beforeDestroy() {
this.isDestroyed = true
this.timeoutnum && clearTimeout(this.timeoutnum)
this.timeoutObj && clearTimeout(this.timeoutObj)
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
this.ws.close() // 关闭ws
},
methods: {
// 进入页面创建websocket连接
initWebSocket() {
const _this = this
// 判断页面有没有存在websocket连接
if (window.WebSocket) {
_this.ws = new WebSocket(websocketUrl + _this.drillId)
_this.ws.onopen = function(e) {
console.log('服务器连接成功')
_this.start() // 开启心跳
}
_this.ws.onclose = function(e) {
console.log('服务器连接关闭')
_this.reconnect() // 重连
}
_this.ws.onerror = function(e) {
console.log('服务器连接出错')
_this.reconnect() // 重连
}
_this.ws.onmessage = function(e) {
_this.reset() // 心跳重置
// 接收服务器返回的数据
const resData = JSON.parse(e.data)
if (resData.isHeartbeat) { // 心跳消息
console.log(new Date().format('HH:mm:ss') + ':' + resData.message)
return
}
// 业务消息
}
}
},
// 重新连接
reconnect() {
var self = this
if (self.lockReconnect || self.isDestroyed) {
return
}
console.log('重新连接。。。')
self.lockReconnect = true
// 没连接上会一直重连,间隔5秒连接一次
self.timeoutnum && clearTimeout(self.timeoutnum)
self.timeoutnum = setTimeout(function() {
// 新连接
self.initWebSocket()
self.lockReconnect = false
}, 5000)
},
// 重置心跳
reset() {
var self = this
// 清除时间
self.timeoutObj && clearTimeout(self.timeoutObj)
self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
// 重启心
self.start()
},
// 开启心跳
start() {
var self = this
self.timeoutObj && clearTimeout(self.timeoutObj)
self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
self.timeoutObj = setTimeout(function() {
// 这里发送一个心跳,后端收到后,返回一个心跳消息
if (self.ws.readyState === 1) { // 判断连接是否正常
const ojb_params = {
isHeartbeat: true,
userWsId: self.userId + '-pc',
contentText: '心跳中'
}
self.ws.send(JSON.stringify(ojb_params))
} else { // 否则重连
self.reconnect()
}
self.serverTimeoutObj = setTimeout(function() {
self.ws.close() // 超过3秒没收到心跳消息关闭重连
}, 3000)
}, self.timeout)
}
}
}
更多推荐
已为社区贡献17条内容
所有评论(0)