uniapp中使用websocket记录

200 阅读2分钟
// @/utils/websocket.js
import { isJSON } from "./utils.js";
import { socketUrl } from "../base.js";

class WebSocketClass {
  constructor(url = socketUrl) {
    this.lockReconnect = false; // 是否开始重连
    this.wsUrl = ""; // ws 地址
    this.globalCallback = null; // 回调方法
    this.userClose = false; // 是否主动关闭
    this.createWebSocket(url);
    // 心跳相关
    this.timeout = 30000;
    this.timeoutObj = null;
    this.serverTimeoutObj = null;
  }
  // 初始化
  initEventHandle() {
    /**
     * 监听WebSocket连接打开成功
     */

    // #ifdef H5
    this.ws.onopen = (event) => {
      this.start();
      console.log("WebSocket连接打开");
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onOpen((res) => {
      this.start();
      console.log("WebSocket连接打开");
    });
    // #endif

    /**
     * 连接关闭后的回调函数
     */

    // #ifdef H5
    this.ws.onclose = (event) => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onClose(() => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    });
    // #endif

    /**
     * 报错时的回调函数
     */

    // #ifdef H5
    this.ws.onerror = (event) => {
      this.reconnect(this.wsUrl); //重连
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onError(() => {
      this.reconnect(this.wsUrl); //重连
    });
    // #endif

    /**
     * 收到服务器数据后的回调函数
     */

    // #ifdef H5
    this.ws.onmessage = (event) => {
      if (isJSON(event.data)) {
        const jsonobject = JSON.parse(event.data);

        this.globalCallback(jsonobject);
      } else {
        this.globalCallback(event.data);
      }
      this.start();
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onMessage((event) => {
      console.log("收到消息", event.data);
      if (isJSON(event.data)) {
        const jsonobject = JSON.parse(event.data);

        this.globalCallback(jsonobject);
      } else {
        this.globalCallback(event.data);
      }
      this.start();
    });
    // #endif
  }
  createWebSocket(url) {
    // #ifdef H5
    if (typeof WebSocket === "undefined") {
      this.writeToScreen("您的浏览器不支持WebSocket,无法获取数据");
      return false;
    }
    // #endif

    // #ifdef APP-PLUS
    if (typeof uni.connectSocket === "undefined") {
      this.writeToScreen("您的浏览器不支持WebSocket,无法获取数据");
      return false;
    }
    // #endif

    this.wsUrl = url;
    try {
      // 创建一个this.ws对象【发送、接收、关闭socket都由这个对象操作】

      // #ifdef H5
      this.ws = new WebSocket(this.wsUrl);
      this.initEventHandle();
      // #endif

      // #ifdef APP-PLUS
      this.ws = uni.connectSocket({
        url: this.wsUrl,
        success: (data) => {
          console.log("websocket连接成功");
          this.start();
          this.initEventHandle();
        },
      });
      // #endif
    } catch (e) {
      this.reconnect(url);
    }
  }

  // 关闭ws连接回调
  reconnect(url) {
    if (this.lockReconnect) return;
    this.ws.close();
    this.lockReconnect = true; // 关闭重连,没连接上会一直重连,设置延迟避免请求过多
    setTimeout(() => {
      this.createWebSocket(url);
      this.lockReconnect = false;
    }, 1000);
  }

  // 发送信息方法
  webSocketSendMsg(msg) {
    this.ws &&
      this.ws.send({
        data: msg,
        success: () => {
          console.log("消息发送成功");
        },
        fail: (err) => {
          console.log("关闭失败", err);
        },
      });
  }

  // 获取ws返回的数据方法
  getWebSocketMsg(callback) {
    this.globalCallback = callback;
  }

  // 关闭ws方法
  closeSocket() {
    if (this.ws) {
      this.userClose = true;
      this.ws.close({
        success: (res) => {
          console.log("关闭成功", res);
        },
        fail: (err) => {
          console.log("关闭失败", err);
        },
      });
    }
  }

  writeToScreen(massage) {
    console.log(massage);
  }
  // 心跳
  start() {
    this.timeoutObj && clearTimeout(this.timeoutObj);
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
    // 15s之内如果没有收到后台的消息,则认为是连接断开了,需要重连
    this.timeoutObj = setTimeout(() => {
      this.writeToScreen("心跳检查,发送ping到后台");
      try {
        const datas = { ping: true };
        this.webSocketSendMsg(JSON.stringify(datas));
      } catch (err) {
        this.writeToScreen("发送ping异常");
      }
      // console.log("内嵌定时器this.serverTimeoutObj: ", this.serverTimeoutObj)
      // 内嵌定时器
      this.serverTimeoutObj = setTimeout(() => {
        this.writeToScreen("没有收到后台发送得消息, 重新连接")
        this.reconnect(this.wsUrl)
      }, this.timeout)
    }, this.timeout)
  }
  reset() {
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    this.start();
  }
  // 停止
  stop() {
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
  }
}
export default WebSocketClass;