前端websocket实体类,开箱即用

前端websocket实体类,开箱即用

class WebSocketUtil {
   
  //isReady默认是false,不自动重连
  constructor(data, callback, isReady = false) {
   
    this.wsData = data;
    this.callback = callback;
    this.isReady = isReady;
    this.createWebSocket();
  }

  reconnect() {
   
    if (this.wsData.lockReconnect) {
   
      return;
    }
    const _this = this;
    this.wsData.lockReconnect = true;
    // 没连接上会一直重连,设置延迟避免请求过多
    this.wsData.tt && clearTimeout(this.wsData.tt);
    this.wsData.tt = setTimeout(function () {
   
      _this.createWebSocket();
      _this.wsData.lockReconnect = false;
    }, 4000);
  }

  isOpen(ws) {
   
    return ws.readyState === ws.OPEN;
  }

  createWebSocket() {
   
    const _this = this;
    const heartCheck = {
   
      // 心跳
      timeout: 20000, // 心跳每20秒发一次
      timeoutObj: null,
      serverTimeoutObj: null,
      start: function () {
   
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        // this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function () {
   
          if (_this.wsData.ws.readyState == 3 && _this.isReady) {
   
            _this.reconnect();
            return;
          }
          if (!_this.isOpen(_this.wsData.ws)) {
   
            clearTimeout(self.timeoutObj);
            return;
          }
          _this.wsData.ws.send(
            JSON.stringify({
   
              type: -1,
            })
          );
        }, this.timeout);
      },
    };
    try {
   
      if (this.wsData.ws) {
   
        this.wsData.ws.close();
      }
      const key = `bearer${
     sessionStorage.getItem("YJZN_TOKEN")}`;
      this.wsData.ws = new WebSocket(`${
     this.wsData.wsUrl}`, key);
    } catch (error) {
   
      //
      console.log("error catch", error);
      this.reconnect(_this.wsData);
      return;
    }

    this.wsData.ws.onopen = function () {
   
      // 这里用一个延时器模拟事件
      console.log("webscoket onOpen", _this.wsData);
      // 心跳检测重置
      heartCheck.start();
    };

    this.wsData.ws.onmessage = function (e) {
   
      // 这里接受服务器端发过来的消息
      let data = null;
      try {
   
        data = JSON.parse(e.data);
      } catch (error) {
   
        data = e ? e.data : null;
      }
      _this.callback(data);
      // 心跳检测重置
      heartCheck.start();
    };
    this.wsData.ws.onclose = () => {
   
      console.log("websocket onclose", _this.wsData);
      _this.isReady && this.reconnect(_this.wsData);
    };
    this.wsData.ws.onerror = () => {
   
      console.log("webscoket onerror", _this.wsData);
      _this.isReady && this.reconnect(_this.wsData);
    };
  }

  getData() {
   
    return this.wsData;
  }
}

export default WebSocketUtil;

export const webSocketClient = (data, callback) => {
   
  return new WebSocketUtil(data, callback);
};

使用方法

import {
    webSocketClient } from '@/utils/websocket';
const fnws = {
   
    wsUrl: '',
    lockReconnect: false,
    ws: null,
    tt: null
};

 if (fnws.ws) {
   
      fnws.ws.close();
 }
fnws.wsUrl = `${
     location.protocol.indexOf('https') != -1 ? 'wss' : 'ws'}://${
     location.host}/ncxjws/alarmWs`;
//调用即可       
webSocketClient(fnws, this.handMsg);

相关推荐

  1. 前端websocket实体开箱

    2023-12-22 18:54:02       40 阅读
  2. Socket.D 替代原生 WebSocket前端开发

    2023-12-22 18:54:02       38 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-22 18:54:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-22 18:54:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-22 18:54:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-22 18:54:02       20 阅读

热门阅读

  1. uni-app上传音频,图片步骤

    2023-12-22 18:54:02       31 阅读
  2. Spring启用https

    2023-12-22 18:54:02       51 阅读
  3. C语言 空指针导致内存溢出

    2023-12-22 18:54:02       43 阅读
  4. Cookie中的Expiry标示是什么

    2023-12-22 18:54:02       37 阅读
  5. ZooKeeper 集群搭建

    2023-12-22 18:54:02       42 阅读
  6. OpenVAS 故障排除

    2023-12-22 18:54:02       35 阅读
  7. FlinkSQL

    FlinkSQL

    2023-12-22 18:54:02      31 阅读
  8. Android Studio 显示Cause: connect timed out

    2023-12-22 18:54:02       38 阅读