【W(wǎng)eb】WebSocket 封裝

WebSocketReconnect 工具類:

class WebSocketReconnect {
  private url: string;
  private socket: WebSocket | null = null;
  private reconnectCount = 0;
  private reconnectTimeout: NodeJS.Timeout | null = null;
  private startTime: number | null = null;
  private listerEvent: Map<string, Function[]> = new Map();
  private manuallyClosed = false;

  constructor(
    url: string,
    private maxReconnectAttempts = 3,
    private reconnectInterval = 20000,
    private maxReconnectTime = 180000
  ) {
    if (!this.isValidWebSocketUrl(url)) {
      throw new Error("Invalid WebSocket URL. Please check the URL format.");
    }
    this.url = url;
    this.connect();
  }

  /**
   * 檢查 WebSocket URL 是否有效
   * @param url WebSocket URL
   * @returns 是否有效
   */
  private isValidWebSocketUrl(url: string = this.url): boolean {
    return /^wss?:\/\/.+/i.test(url);
  }

  /**
   * 建立 WebSocket 連接
   */
  private connect(): void {
    console.log("Connecting to WebSocket...");

    this.manuallyClosed = false; // 重置手動關(guān)閉標志位
    this.socket = new WebSocket(this.url);

    // 綁定事件
    this.socket.onopen = () => {
      console.log("WebSocket Connection Opened!");
      this.triggerEvent("open");
      this.clearReconnectTimeout();
      this.reconnectCount = 0;
    };

    this.socket.onmessage = (event: MessageEvent) => {
      console.log("WebSocket Message Received:", event.data);
      this.triggerEvent("message", event.data);
    };

    this.socket.onclose = (event: CloseEvent) => {
      console.log("WebSocket Connection Closed:", event);
      this.triggerEvent("close", event);
      if (!this.manuallyClosed) {
        this.handleReconnect();
      }
    };

    this.socket.onerror = (error: Event) => {
      console.error("WebSocket Error Occurred:", error);
      this.triggerEvent("error", error);
      if (!this.manuallyClosed) {
        this.handleReconnect();
      }
    };
  }

  /**
   * 處理斷線重連邏輯
   */
  private handleReconnect(): void {
    if (
      this.reconnectCount < this.maxReconnectAttempts &&
      (this.startTime === null || Date.now() - this.startTime < this.maxReconnectTime)
    ) {
      this.reconnectCount++;
      console.log(
        `Attempting to reconnect (${this.reconnectCount}/${this.maxReconnectAttempts})...`
      );

      if (!this.startTime) {
        this.startTime = Date.now();
      }

      this.reconnectTimeout = setTimeout(() => {
        this.connect();
      }, this.reconnectInterval);
    } else {
      console.log("Max reconnect attempts or time exceeded. Giving up.");
      this.reconnectCount = 0;
      this.startTime = null;
    }
  }

  /**
   * 清除重連定時器
   */
  private clearReconnectTimeout(): void {
    if (this.reconnectTimeout) {
      clearTimeout(this.reconnectTimeout);
      this.reconnectTimeout = null;
    }
  }

  /**
   * 觸發(fā)注冊的事件
   * @param type 事件類型
   * @param args 事件參數(shù)
   */
  private triggerEvent(type: string, ...args: any[]): void {
    const callbacks = this.listerEvent.get(type) || [];
    callbacks.forEach((callback) => callback(...args));
  }

  /**
   * 添加事件監(jiān)聽器
   * @param type 事件類型
   * @param callback 回調(diào)函數(shù)
   */
  public on(type: string, callback: Function): void {
    if (!this.listerEvent.has(type)) {
      this.listerEvent.set(type, []);
    }
    this.listerEvent.get(type)!.push(callback);
  }

  /**
   * 發(fā)送消息
   * @param message 要發(fā)送的消息
   */
  public send(message: string | ArrayBuffer | Blob): void {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    } else {
      console.error("WebSocket is not open. Unable to send message.");
    }
  }

  /**
   * 手動關(guān)閉 WebSocket 連接
   */
  public close(): void {
    this.manuallyClosed = true;
    this.clearReconnectTimeout();
    if (this.socket) {
      this.socket.close();
    }
    this.reconnectCount = 0;
    this.startTime = null;
  }

  /**
   * 查詢 WebSocket 當(dāng)前狀態(tài)
   * @returns WebSocket 狀態(tài)
   */
  public getState(): string {
    if (!this.socket) {
      return "DISCONNECTED";
    }
    switch (this.socket.readyState) {
      case WebSocket.CONNECTING:
        return "CONNECTING";
      case WebSocket.OPEN:
        return "OPEN";
      case WebSocket.CLOSING:
        return "CLOSING";
      case WebSocket.CLOSED:
        return "CLOSED";
      default:
        return "UNKNOWN";
    }
  }

  /**
   * 動態(tài)更新 WebSocket URL 并重新連接
   * @param newUrl 新的 WebSocket URL
   */
  public updateUrl(newUrl: string): void {
    if (!this.isValidWebSocketUrl(newUrl)) {
      throw new Error("Invalid WebSocket URL.");
    }
    this.close();
    this.url = newUrl;
    this.connect();
  }
}

export default WebSocketReconnect;

使用示例:

const ws = new WebSocketReconnect("wss://example.com", 5, 5000, 300000);

ws.on("open", () => console.log("WebSocket connected!"));
ws.on("message", (msg) => console.log("Received message:", msg));
ws.on("close", () => console.log("WebSocket closed."));
ws.on("error", (err) => console.error("WebSocket error:", err));

ws.send("Hello, server!");
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容