解决问题:
因为计算机休眠、网络不稳定等原因,导致实时监视页面的websocket数据推送断了,数据不再更新没有实时性。
目的效果:
当websocket断开连接时马上重连,依然断开则1分钟后再重连,直到连接成功为止。
注意: 当切换页面等正常销毁websocket排除在此机制外。可通过设置timerFlagWS以及关闭时的状态码e.code判断是否重连。
代码:
let websock = null
let socketTimer = null
let socketParam = {
type: 'test'
}
export default {
name: 'test',
data () {
return {
socketUrl: 'ws://IP:PORT',
timerWS: null, // 用于ws重连
timerCountWS: 0, // 用于重连计数,0-立刻开始重连,非0-1min重连一次。
timerFlagWS: true // 跳转页面了不再重连
}
},
mounted () {
this.initWebsocket()
},
destroyed () {
// 关闭websocket
this.timerFlagWS = false
this.timerCountWS = 0
clearTimeout(this.timerWS)
if (websock !== null) {
websock.close()
websock = null
}
clearTimeout(socketTimer)
},
methods: {
initWebsocket () {
if (typeof WebSocket !== 'undefined') {
this.timerCountWS++
// 浏览器支持Websocket通信协议 开启长连接
websock = new WebSocket(this.socketUrl)
websock.onopen = this.websocketonopen
websock.onclose = this.websocketclose
websock.onerror = this.websocketonerror
websock.onmessage = this.websocketonmessage
} else {
// 浏览器不支持Websocket通信协议
this.$message.info('当前浏览器不支持Websocket通信协议,建议使用Chrome或者Firefox浏览器!')
}
},
// 开启
websocketonopen () {
console.log('websocketonopen [test]')
this.timerCountWS = 0
this.threadPoxi()
},
// 关闭
websocketclose (e) {
console.log(e, 'websocketclose [test]')
let self = this
if (self.timerCountWS === 0) {
if (self.timerFlagWS && e.code === 1006) self.initWebsocket()
console.log('websocket reconnect:[test ' + self.timerCountWS + ']', self.timerFlagWS)
} else {
clearTimeout(self.timerWS)
self.timerWS = setTimeout(() => {
if (self.timerFlagWS && e.code === 1006) self.initWebsocket()
console.log('websocket reconnect:[test ' + self.timerCountWS + ']', self.timerFlagWS)
}, 60000)
}
},
// 错误
websocketonerror (e) {
console.log('websocketonerror [test]')
},
// 数据接收
websocketonmessage (e) {
let res = JSON.parse(e.data)
console.log(res, 'websocket推送结果')
},
threadPoxi () {
// 参数
let self = this
// 若是ws开启状态
if (websock.readyState === websock.OPEN) {
console.log('websock.OPEN, websock.send start... [test]')
self.websocketsend(socketParam)
} else if (websock.readyState === websock.CONNECTING) {
// 若是正在开启状态 则等待300毫秒 再调threadPoxi判断状态
console.log('websock.CONNECTING, please wait 300ms... [test]')
clearTimeout(socketTimer)
socketTimer = setTimeout(() => {
self.threadPoxi()
}, 300)
} else {
// 若未开启 初始化websocket
console.log('websock is not open, wait for reboot... [test]')
self.initWebSocket()
}
},
// 数据发送
websocketsend (param) {
websock.send(JSON.stringify(param))
}
}
}
复制代码
补充:
此处websocket的请求地址相当于写死在此处,应当使用nginx代理通过配置在nginx.config文件中便于修改。