websocket断网重连

解决问题:

因为计算机休眠、网络不稳定等原因,导致实时监视页面的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)
  }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值