websocket - 心跳机制 - pc端

webSocket () {
      const that = this
      // let socket
      if (window.WebSocket) {
        let locationOrigin = window.location.origin.replace('http://', '')
        let header = 'ws://'
        if (window.location.origin.startsWith('https')) {
          header = 'wss://'
          locationOrigin = window.location.origin.replace('https://', '')
        }
        that.ws = new WebSocket(header + locationOrigin + '/websocket' + '?' + sessionStorage.getItem('userCode') +
        ',;' + sessionStorage.getItem('token') + ',;' + sessionStorage.getItem('authToken') + ',;' + '1')
        // that.ws = new WebSocket('ws://' + that.webSocketPath)
        // 监听socket连接
        that.ws.onopen = function () {
          // that.ws = socket
          that.start()
          that.ws.send(
            JSON.stringify({
              userCode: sessionStorage.getItem('userCode')
            })
          )
        }
        // 监听socket消息
        that.ws.onmessage = function (msg) {
          // 写自己的处理逻辑
          console.log('接收message', msg.data)
          // 收到服务器信息,心跳重置
          // that.reset()
        }
        // 监听socket错误信息
        that.ws.onerror = that.websocketerror()
        // 监听socket关闭
        that.ws.onclose = that.websocketclose()
      }
    },
    websocketerror () {
      // console.log('onerror')
      this.reconnect()
    },
    websocketclose () {
      // console.log('onclose')
      // this.reconnect()
      let that = this
      clearInterval(that.timeIntervalObj)
      clearTimeout(that.serverTimeoutObj)
    },
    // 开始心跳
    start () {
      let self = this
      self.timeIntervalObj && clearInterval(self.timeIntervalObj)
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
      self.timeIntervalObj = setInterval(function () {
        if (self.ws.readyState === 1) {
          // 连接正常
          self.ws.send('heartCheck') // 发送心跳
          // console.log('heartCheck')
        } else {
          // console.log('timeout-reconnect')
          self.reconnect() // 重新连接
        }
        // self.serverTimeoutObj = setTimeout(function () {
        //   // 超时关闭
        //   self.ws.close()
        //   console.log('timeout-close')
        // }, self.timeout)
      }, self.timeout)
    },
    // 重置心跳
    reset () {
      // console.log('reset')
      let that = this
      clearInterval(that.timeIntervalObj)
      clearTimeout(that.serverTimeoutObj)
      that.start()
    },
    // 重连
    reconnect () {
      // console.log('reconnect')
      let that = this
      if (that.lockReconnect) {
        return
      }
      that.lockReconnect = true
      that.timeoutnum && clearTimeout(that.timeoutnum)
      that.timeoutnum = setTimeout(function () {
        // console.log('reconnect-webSocket')
        // 新连接
        that.webSocket()
        that.lockReconnect = false
      }, 5000)
    },

      // 消息相关
      ws: null, // WebSocket实例
      webSocketPath: 'localhost:13222', // 地址
      lockReconnect: false, // 是否真正建立连接
      timeout: 8 * 1000, // 心跳检测时间
      timeIntervalObj: null, // 心跳心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时

uniapp中使用websoket 可参考 uniapp websocket连接 心跳机制_不秃头的小姑娘的博客-CSDN博客

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值