vue中使用WebSocket

醉菜鸟 2022-06-27 08:00:18

简单封装的vue websocket 的使用

export default {
  ws: null,
  clientID: '',
  callBackMapping: {},
  connected: false,
  sendRetryCount: 0,
  connectRetryCount: 0,
  connect() {
    if (!window.WebSocket) {
      return console.log('Does not support WebSocket')
    }
    this.ws = new WebSocket('ws地址')
    this.ws.onopen = (e) => {
      this.connected = true
      this.connectRetryCount = 0
      this.callBackMapping['onopen'] && this.callBackMapping['onopen'](e)
    }
    this.ws.onerror = (e) => {
      this.connected = false
      this.connectRetryCount++
      this.callBackMapping['onerror'] && this.callBackMapping['onerror'](e)
      setTimeout(() => {
        this.connect()
      }, 500 * this.connectRetryCount)
    }

    this.ws.onclose = (e) => {
      this.callBackMapping['onclose'] && this.callBackMapping['onclose'](e)
    }

    this.ws.onmessage = e => {
      const data = JSON.parse(e.data)
      this.callBackMapping['onmessage'] && this.callBackMapping['onmessage'](data)
    }

    return this
  },
  close() {
    this.ws.close()
  },
  registerCallBack(socketType, callBack) {
    this.callBackMapping[socketType] = callBack
  },
  unRegisterCallBack(socketType) {
    this.callBackMapping[socketType] = null
  },
  send(data) {
    if (this.connected) {
      this.sendRetryCount = 0
      try {
        this.ws.send(data)
      } catch (e) {
        this.ws.send(data)
      }
    } else {
      this.sendRetryCount++
      setTimeout(() => {
        this.send(data)
      }, this.sendRetryCount * 500)
    }
  }
}
意见反馈