解决问题:
因为计算机休眠、网络不稳定等原因,导致实时监视页面的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)
}