前端websocket封装+自动重连+心跳

websocket封装

自己项目封装使用的,仅供参考。

/**
 * websocket 封装
 * 自动重连
 */
 // export default class MSocket {
export class MSocket {
  constructor (config) {
    if (!config.url) {
      throw new Error('websocket url is invalid')
    }
    this.reconnectTimer = null
    this.heartbeatTimer = null
    this.isAlive = false
    this.config = {
      url: '',
      retry: Infinity,
      reconnectWait: 5 * 1000,
      heartBeatWait: 6 * 1000,
      heartMsg: 'test',
      isHeartBeat: true
    }
    Object.keys(config).forEach(key => {
      this.config[key] = config[key]
    })
    this.init()
  }

  init () {
    this.socket = new WebSocket(this.config.url)

    this.socket.onerror = (e) => {
      this.reconnect()
      this.isAlive = false
      typeof this.config.onerror === 'function' && this.config.onerror(e)
    }

    this.socket.onmessage = ({ data }) => {
      const res = data.indexOf('{') > -1 ? JSON.parse(data) : data
      typeof this.config.onmessage === 'function' && this.config.onmessage(res)
    }

    this.socket.onclose = (e) => {
      this.isAlive = false
      console.info('websocket was closed')
      typeof this.config.onclose === 'function' && this.config.onclose(e)
    }

    this.socket.onopen = (e) => {
      console.info('websocket was opened')
      this.isAlive = true
      if (this.config.isHeartBeat) {
        this.startHeart()
      }
      typeof this.config.onopen === 'function' && this.config.onopen(e)
    }
  }

  send (data) {
    if (!this.isAlive) return
    const text = typeof data === 'string' ? data : JSON.stringify(data)
    this.socket.send(text)
  }

  reconnect () {
    this.reconnectTimer = setTimeout(() => {
      if (this.config.retry > 0) {
        this.config.retry--
        this.init()
      }
    }, this.config.reconnectWait)
  }

  startHeart () {
    this.heartbeatTimer = setInterval(() => {
      this.send(this.config.heartMsg)
    }, this.config.heartBeatWait)
  }
}

使用方法

import { MSocket } from '/your path/socket'
const websocket = new MSocket({
        url: 'your ws url',
        onerror: (e) => {
          console.log(e)
        },
        onmessage: (data) => {
          console.log(data)
        }
      })
websocket.send('666')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值