socket连接封装

效果:

javascript 复制代码
class websocketMessage {
  constructor(params) {
    this.params = params; // 传入的参数
    this.socket = null;
    this.lockReconnect = false; // 重连的锁
    this.socketTimer = null; // 心跳
    this.lockTimer = null; // 重连
    this.timeout = 3000; // 发送消息
    this.callbacks = []; // 存储外部的回调函数
    // this.init(); // websocket 初始化
  }

  /**
   * @description: websocket 初始化
   * @return {*}
   */
  init() {
    if (!("WebSocket" in window)) {
      console.warn("当前浏览器不支持 WebSocket");
      return;
    }

    this.lockReconnect = false;
    this.socket = new WebSocket(this.params.ws);
    this.socket.onopen = this.open.bind(this);
    this.socket.onmessage = this.onMessage.bind(this);
    this.socket.onerror = this.error.bind(this);
    // this.socket.onclose = this.close.bind(this);
  }

  /**
   * @description: websocket 已连接
   * @return {*}
   */
  open() {
    console.log(`${this.params.ws}:WebSocket已连接。`);
  }

  /**
   * @description: 监听接收消息
   * @param {*} event
   * @return {*}
   */
  onMessage({
    data
  }) {


    // 判断是否开启心跳
    if (this.params.heart) {
      this.socketTimer && clearTimeout(this.socketTimer);
      this.socketTimer = setTimeout(() => {
        this.socket.send(JSON.stringify(this.params.heart.data));
      }, 3000);
    }

    // 如果开启心跳,过滤掉心跳的数据
    if (data === this.params?.heart?.data) {
      return;
    }
    // 将消息传递给所有注册的回调函数
    this.callbacks.forEach((callback) => callback(typeof data === 'string' ? data : JSON.parse(data)));
  }

  /**
   * @description: 注册消息回调函数
   * @param {*} callback 回调函数
   * @return {*}
   */
  message(callback) {
    if (typeof callback === "function") {
      this.callbacks.push(callback);
    } else {
      console.warn("注册的回调必须是一个函数");
    }
  }

  /**
   * @description: 发送消息
   * @param {*} msg
   * @return {*}
   */
  send(msg) {
    if (!this.socket) {
      return;
    }
    let timer = null;
    clearTimeout(timer);
    timer = setTimeout(() => {
      if (this.socket?.readyState === 1) {
        this.socket.send(JSON.stringify(msg));
        clearTimeout(timer);
      } else {
        this.send(msg);
      }
    }, 50);
  }

  /**
   * @description: 连接发送错误的时候,输出信息
   * @param {*} e 错误消息
   * @return {*}
   */
  error(e) {
    this.socket = null;
    console.log(`${this.params.ws}:WebSocket正在重新连接`, e);
    this.reconnect();
  }

  /**
   * @description: 关闭 websocket 连接
   * @return {*}
   */
  close() {
    this.socket = null;
    this.lockReconnect = true;
    this.callbacks = []; // 清除回调
    clearTimeout(this.lockTimer);
    clearTimeout(this.socketTimer);
    this.socket?.onclose();
    console.log(`${this.params.ws}:WebSocket连接已关闭`);
  }

  /**
   * @description: 重新连接 websocket
   * @return {*}
   */
  reconnect() {
    if (this.lockReconnect) {
      return;
    }
    this.lockReconnect = true;
    clearTimeout(this.lockTimer);
    this.lockTimer = setTimeout(() => {
      this.init();
    }, this.timeout);
  }
}



// 调用:
let socket = new websocketMessage({
  ws: "wss://toolin.cn/echo",
});

socket.init();

// 注册消息处理回调
socket.message((data) => {
  console.log("接收到的消息:", data);
});

// 发送登录消息
socket.send({
  type: "login",
  data: {
    userId: "123",
  },
});
setTimeout(() => {

  // 发送登录消息
  socket.send({
    type: "sadfasd",
    data: {
      userId: "sadf",
    },
  });
}, 5000)
setTimeout(() => {

  // 发送登录消息
  socket.send({
    type: "20000",
    data: {
      userId: "2",
    },
  });
}, 2000)
相关推荐
ct97823 分钟前
vue2 + vue3差异点
前端·javascript·vue.js
小徐_233333 分钟前
程序员每天盯屏 10 小时,我开始认真研究“专业编程屏”这件事
前端
悟空瞎说43 分钟前
Git 协作工作流详解:从个人单打独斗到规模化团队协同
前端·git
颜进强1 小时前
20-Spec-Kit Tasks 是怎么把技术方案拆成可执行任务的?
前端·后端·ai编程
程序员鱼皮1 小时前
Cursor 零基础实战教程,夯爆了!带你速通 6 大核心能力
前端·后端·ai编程
颜进强1 小时前
14-Spec-Kit、SDD 和 OpenSpec 到底有什么区别?其实核心思想都一样:先写清楚,再让 AI 干活
前端·后端·ai编程
颜进强1 小时前
16-Spec-Kit 是什么?先从整体流程机制讲起
前端·后端·ai编程
悟空瞎说1 小时前
QML 集成 WebView 开发桌面内嵌浏览器实战
前端
前端与小赵1 小时前
快速生成安卓证书并打包生成安卓apk(保姆教程)
android·前端
Cxiaomu1 小时前
MentorPi A1 底盘接入开发实践:让自研Web系统接管机器人底盘
前端·机器人