websocket的封装1(做vue中的通信经常也是大概率用到的)

darylove 2019-12-27

export default class WebSocketClass {



  constructor(url, msgCallback, time) {
    const
      IS_HTTPS = document.location.protocol.includes(‘https‘)  //容错 http https
    const
      wsProtocol = IS_HTTPS ? ‘wss://‘ : ‘ws://‘
    this.wsUrl = `${wsProtocol}${url}`
    this.msgCallback = msgCallback;
    this.time = time;     //心跳时间
    this.initTime = 5000   //重连时间
    this.init()
  }

  init(data) {

    let WSINWIN = ‘WebSocket‘ in window
    if (!WSINWIN) {
      return console.log(‘Websocket not supported‘)
    }
    this.ws = new WebSocket(this.wsUrl);
   // console.log(‘new 成功‘);
    this.ws.onopen = () => {
      this.status = ‘open‘;
      this.heartCheck();
      if(data){this.ws.send(data)}
    };

    this.ws.onmessage = e => {
      if (e.data === ‘pong‘){
        this.pingPong = ‘pong‘
      }else {
        this.msgCallback(e.data);
      }
    };

    this.ws.onclose = (e) => {
      clearInterval(this.pingInterval);
      clearInterval(this.pongInterval)
      if (this.status === ‘close‘) {
        //console.log(‘手动关闭成功‘,new Date())
      }else{
        //console.log(‘非手动关闭,重新连接 relink‘,new Date());
        this.relink();  //非人为关闭进行重连
      }

    }

    this.ws.onerror = e => {
        console.log(e);
      this.relink()
    }
    return false
  }

  heartCheck() {          // 心跳
    this.pingPong = ‘ping‘;
    let timer= this.time +1000
    this.pingInterval = setInterval(() => {
      if (this.ws.readyState === 1){
        //console.log(‘ping‘,new Date());
        this.ws.send(‘ping‘)
      }
    }, this.time);
    this.pongInterval = setInterval(() => {
      if (this.pingPong === ‘ping‘){
        //console.log(‘pong未返回,准备关闭‘,new Date());
        clearInterval(this.pingInterval);
        clearInterval(this.pongInterval)

        this.ws.close()
      }else{
        //console.log(‘pong‘,new Date());
        this.pingPong = ‘ping‘
      }
    }, timer)
  }

  sendHandle(data) {
    return this.ws.send(data);
  }

  relink() {
   // console.log(‘开始重新连接‘);
    if (this.status == ‘open‘ && this.readyState == 1) {  //连接正常
      //console.log(‘状态正常,无需重新连接‘,new Date());
      return
    }
    if (this.initTimeOut) { //定时器已经启动
      //console.log(‘正在重连,定时器已启动,退出‘,new Date());
      return;
    }
    this.initTimeOut = setTimeout(() => {
      //console.log(‘重新连接 初始化‘,new Date());
      clearInterval(this.pingInterval);
      clearInterval(this.pongInterval);
      this.initTimeOut = null;
      this.init();
    }, this.initTime)
  }

// 手动关闭WebSocket
  closeMyself() {
    console.log(‘执行手动关闭‘,new Date());
    this.status = ‘close‘;
    this.ws.close();
  }
}

相关推荐