class类 封装websocket

856 阅读2分钟

用过class类封装websocket。 简单封装只有获取推送过来的 数据 没有做向服务端发送数据。

 * @desc websocket 类
 * @param {String} path 连接地址
 * @param {Function} onmessage 连接地址
 * @return 
 * @author ppc
 * @date 2022-08-29 11:20:58
 */
import {
  Message
} from 'element-ui'
export class dsWebSocket {
  constructor(params) {
    this.params = params
    this.wesock = null // 建立的连接
    this.lockReconnect = false // 是否真正的建立连接
    this.timeout = 10 * 1000, // n秒一次的心跳
    this.timeoutObj = null // 心跳倒计时
    this.serverTimeoutObj = null // 心跳倒计时
    this.timeoutnum = null // 断开 重连倒计时
    console.log(this,'this constructor')
    if ('WebSocket' in window) {
      this.init(params)
    } else {
      Message({
        message: "浏览器不支持,请换浏览器再试",
        type: "error"
      });
    }
  }

  /**
   * @desc 初始化
   * @param 
   * @return 
   * @author ppc
   * @date 2022-08-29 11:21:21
   */
  init(params) {
    //建立连接
    this.websock = new WebSocket(params.path)
    // 连接成功
    this.websock.onopen = this.onOpen.bind(this)
    //连接错误
    this.websock.onerror = this.onError.bind(this)
    //接收信息
    this.websock.onmessage = this.getInformation.bind(this)

    //连接关闭
    this.websock.onclose = function () {}
    this.websock.onclose = this.close.bind(this)
  }

  /**
   * @desc 重新连接
   * @param 
   * @return 
   * @author ppc
   * @date 2022-08-29 11:37:36
   */
  reconnect() {
    if (this.lockReconnect) {
      return
    }
    this.lockReconnect = true;
    //没连接上会一直重连,设置延迟避免请求过多
    this.timeoutnum && clearTimeout(this.timeoutnum);
    this.timeoutnum = setTimeout(function () {
      //新连接
      this.init();
      this.lockReconnect = false;
    }, 5000);
  }

  /**
   * @desc 重置心跳
   * @param 
   * @return 
   * @author ppc
   * @date 2022-08-29 11:38:05
   */
  reset() {
    console.log('this',this)

    //清除时间
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    
    //重启心跳
    console.log('-----重启心跳------')
    this.start();
  }

  /**
   * @desc 开启心跳
   * @param 
   * @return 
   * @author ppc
   * @date 2022-08-29 11:38:30
   */
  start() {
    this.timeoutObj && clearTimeout(this.timeoutObj);
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
    this.timeoutObj = setTimeout( () =>{
      //这里发送一个心跳,后端收到后,返回一个心跳消息,
      if (this.websock&&this.websock.readyState == 1) {
        // console.log(222222)
        //如果连接正常
        this.websock.send('{"wsRequestType":"HEARTBEAT"}');
        // console.log("发送消息");
      } else {
        //否则重连
        // console.log("重新链接")
        // this.reconnect();
      }
      this.serverTimeoutObj = setTimeout(function () {
        //超时关闭
        this.websock.close();
      }, this.timeout);
    }, this.timeout);
  }

  /**
   * @desc 连接成功
   * @param 
   * @return 
   * @author ppc
   * @date 2022-08-29 11:39:32
   */
  onOpen() {
    //提示成功
    // this.isOnline = 1;
    //开启心跳
    console.log(this,'this')
    console.log('-----连接成功------')
    this.start();
  }

  /**
   * @desc 连接失败
   * @param 
   * @return 
   * @author ppc
   * @date 2022-08-29 11:41:06
   */
  onError() {
    // console.log("WebSocket连接发生错误");
    // this.isOnline = 2;
    //重连
    this.reconnect();
  }

  /**
   * @desc 连接关闭事件
   * @param 
   * @return 
   * @author ppc
   * @date 2022-08-29 11:41:27
   */
  close() {
    // this.reconnect();
  }

  /**
   * @desc 接收服务器推送的信息
   * @param 
   * @return 
   * @author ppc
   * @date 2022-08-29 11:41:59
   */
  getInformation(event) {
    //收到服务器信息,心跳重置
    this.reset();
    const redata = JSON.parse(event.data);
    this.params.onmessage(redata)
    return redata
  }
  /**
   * @desc 向服务器发送信息
   * @param 
   * @return 
   * @author ppc
   * @date 2022-08-29 11:43:33
   */
  send() {

  }

}


     var that = this;
            const webSocket = new dsWebSocket({
                path: wsuri,
                onmessage: function (msg) {
                    console.log(msg, "返回的数据);
                    //数据处理
                    that.websocketonmessage(msg);
                },
            });