美文网首页
websocket心跳包监测

websocket心跳包监测

作者: 叶小七的真命天子 | 来源:发表于2019-05-14 18:00 被阅读0次
    export default class WebSocketClient {
      constructor () {
        this.ws = null // websocket实例
        this.connecting = false // 正在连接
        this.reconnectSettimeout = null // 重新连接的setTimeout
        this.timeout = 3000 // 心跳监测间隔
        this.timeoutObj = null
        this.serverTimeoutObj = null
        this.handleMessage = {}
        this.createWebSocket()
      }
    
      createWebSocket () {
        try {
          this.ws = new WebSocket(process.env.WEBSOCKET_URL)
          this.handlerMessage()
        } catch (error) {
          console.log('catch')
          this.reconnect()
        }
      }
      reconnect () {
        if (this.connecting) return
        this.connecting = true
        this.reconnectSettimeout && clearTimeout(this.reconnectSettimeout)
        this.reconnectSettimeout = setTimeout(() => {
          this.createWebSocket()
          this.connecting = false
        }, 4000)
      }
    
      startHeartcheck () {
        this.timeoutObj && clearTimeout(this.timeoutObj)
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
        this.timeoutObj = setTimeout(() => {
          this.ws.send('ping')
          this.serverTimeoutObj = setTimeout(() => {
            this.ws.close()
          }, this.timeout)
        }, this.timeout)
      }
      handlerMessage () {
        const that = this
        that.ws.onopen = function () {
          console.log('ws has opened')
          this.startHeartcheck()
        }
        that.ws.onmessage = function (e) {
          try {
            this.startHeartcheck()
            const data = JSON.parse(e.data)
            if (data.message && that.handleMessage[data.message]) {
              that.handleMessage[data.message](data)
            }
          } catch (e) {
            console.warn(e)
          }
        }
        that.ws.onclose = function (restart) {
          console.log('ws closed')
          restart && this.reconnect()
        }
        that.ws.onerror = function () {
          console.log('ws erred')
          this.reconnect()
        }
      }
    
      registerHandler (msg, handle) {
        const that = this
        const handler = {}
        handler[msg] = handle
        Object.assign(that.handleMessage, handler)
      }
    
      cancelRegister (msg) {
        if (msg) {
          delete this.handleMessage[msg]
        }
      }
    
      sendMsg (msg) {
        this.ws && this.ws.send(JSON.stringify(msg))
      }
      close (restart) {
        this.ws.close(restart)
      }
    }
    
    

    相关文章

      网友评论

          本文标题:websocket心跳包监测

          本文链接:https://www.haomeiwen.com/subject/zyyeaqtx.html