webscoket 封装

封装ws.js 

export const initWebSocket = class ws {
  constructor(url, messagesFn, openData) {
    //ws地址
    this.wsUrl = url;
    //ws初始化发送的消息
    this.openData = openData || '初始化websocket连接';
    //接收消息的回调
    this.messagesFn = messagesFn;
    //重连开关
    this.reconnectSwitch = true;
    //重连定时器
    this.reconnectTimer = null;
    //心跳定时器
    this.keepAliveTimer = null;
    //心跳消息
    this.keepaliveData = JSON.stringify({
      messageType: 'Heartbeat',
      message: '心跳检测',
    });
    //前次发送失败的消息
    this.tempSendMessage = '';
    //ws对象
    this.websock = null;
    //初始化ws
    this.initWs();
  }

  //初始化ws
  initWs() {
    let that = this;

    this.websock = new WebSocket(that.wsUrl);
    this.websock.onopen = this.onopen.bind(that);
    this.websock.onmessage = this.onmessage.bind(that);
    this.websock.onclose = (e) => {
      that.reconnectWs();
    };
    this.websock.onerror = (e) => {
      that.reconnectWs();
    };
  }

  //ws打开
  onopen() {
    let that = this;

    //关闭旧的定时器
    that.clearWsInterval();

    //发送初始化消息
    if (that.openData) {
      this.send(that.openData);
    }

    //发送前一次发送失败的消息
    if (this.tempSendMessage) {
      let time = setTimeout(() => {
        that.send(that.tempSendMessage);
        that.tempSendMessage = '';
        clearTimeout(time);
      }, 1000);
    }

    //开启保活机制
    this.keepalive();
  }

  //ws接收到消息
  onmessage(message) {
    if (message && message.data) {
      let res = JSON.parse(message.data);
      if (res) {
        //调用页面的消息回调方法
        this.messagesFn(res);
      }
    }
  }

  //ws发送消息
  send(agentData) {
    try {
      this.websock.send(agentData);
    } catch (error) {
      this.tempSendMessage = agentData;
      this.reconnect();
    }
  }

  //主动关闭
  close() {
    this.reconnectSwitch = false;
    this.websock.close();
  }
  // 重连
  reconnectWs() {
    if (this.reconnectSwitch) {
      this.reconnect();
    }
  }

  //保活心跳
  keepalive() {
    let that = this;
    this.keepAliveTimer = setInterval(() => {
      if (that.websock.readyState === 1) {
        // console.log('WebSocket的链接已经建立,正在发送心跳信号');
        that.websock.send(that.keepaliveData);
      }
    }, 5 * 60 * 1000);
  }

  //重连机制
  reconnect() {
    let that = this;
    this.clearWsInterval();

    this.reconnectTimer = setInterval(() => {
      that.initWs();
    }, 3000);
  }

  //清除保活和重连的定时器
  clearWsInterval() {
    let that = this;
    this.reconnectTimer && clearInterval(that.reconnectTimer);
    this.keepAliveTimer && clearInterval(that.keepAliveTimer);
  }
};

调用

initSocket() {
        const userId = getSession('userId'); //用户id,
        const nowDate = new Date().getTime();
        const webSocketUrl = `ws://${baseURL.ws}/websocket/${userId}-${nowDate}`;
        this.ws = new initWebSocket(webSocketUrl, (e) => {
          this.$EventBus.$emit('websocketMessage', e);
        });
      },

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值