封装前端webSocket-基于class

WebSocket 封装库文档

功能概述

本 WebSocket 封装类主要实现以下核心功能:

  • 自动心跳检测机制
  • 断线自动重连
  • 消息事件处理
  • 可控连接关闭
  • 超时断开保护

类结构

构造函数参数

参数名类型说明
tkstring用户认证令牌
onOkCallBackfunction消息接收回调函数
heartbeatboolean是否启用心跳检测
timeoutnumber心跳发送间隔(毫秒)
disconnectTimenumber等待响应超时时间(毫秒)

具体代码

import { apiTypeConfig } from "./common";

class NewWebSocket {
  constructor(props) {
    this.props = props;
    this.tk = props.tk;
    this.onOkCallBack = props.onOkCallBack;
    this.heartbeat = props.heartbeat;
    this.timeout = props.timeout;
    this.disconnectTime = props.disconnectTime;

    this.WS = null;
    this.timeoutObj = null;
    this.reconnectTime = null;
    this.serverTimeoutObj = null;
    this.lockReconnect = false;
  }

  /**
   * 建立联系
   */
  handleCreate() {
    this.heartbeat = this.props.heartbeat;
    const { domain, subdomain } = apiTypeConfig[API_TYPE] || { domain: "", subdomain: "" };
    this.WS = new WebSocket(`wss://${subdomain}.${domain}/websocket/userMessage/${this.tk}`);
    this.WS.onopen = () => {
      if (this.heartbeat) {
        this.handleSend("ping"); //第一次建立连接发送心跳(后端需求)
        this.reset();
        this.start();
      }
    };
    this.WS.onmessage = e => {
      if (this.heartbeat && e.data === "pong") {
        this.reset();
        this.start();
      } else {
        this.onOkCallBack(e.data);
      }
    };
    this.WS.onclose = () => {
      if (this.heartbeat) {
        this.reconnect();
      }
    };
  }

  /**
   * 断开连接
   */
  handleClose(type) {
    if (type === "end") {
      this.heartbeat = false;
      this.reset();
      clearTimeout(this.reconnectTime);
      this.reconnectTime = null;
    }
    this.WS.close();
  }

  /**
   * 发送数据
   * @param e 要发送的数据
   */
  handleSend(e) {
    this.WS.send(e);
  }

  /**
   * 重置心跳
   * @returns {NewWebSocket}
   */
  reset() {
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    this.timeoutObj = null;
    this.serverTimeoutObj = null;
  }

  /**
   * 发送心跳
   */
  start() {
    const that = this;
    that.timeoutObj = setTimeout(function() {
      that.handleSend("ping");
      that.serverTimeoutObj = setTimeout(function() {
        // 如果超过一定时间还没重置,说明后端主动断开了
        that.handleClose();
      }, that.disconnectTime);
    }, that.timeout);
  }

  /**
   * 延迟请求
   */
  reconnect = () => {
    const that = this;
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    this.reconnectTime = setTimeout(function() {
      // 没连接上会一直重连,设置延迟避免请求过多
      that.handleCreate();
      that.lockReconnect = false;
    }, 10000);
  };
}

export default NewWebSocket;

使用示例子

const ws = new NewWebSocket({
  tk: 'your_auth_token',
  onOkCallBack: (data) => {
    console.log('Received:', data);
  },
  heartbeat: true,
  timeout: 30000,      // 30秒发送一次心跳
  disconnectTime: 5000 // 5秒无响应判定超时
});

// 建立连接
ws.handleCreate();

// 发送消息
ws.handleSend('Hello Server');

// 关闭连接
ws.handleClose('end');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值