JS — websocket封裝

萬事順意發表於2024-05-21
class WebSocketRequest {
  constructor(url, options = {}) {
    this.url = url;
    this.socket = null;
    this.requestId = 0;
    this.requests = {};
    this.options = Object.assign({}, options);
    this.connect();
  }

  connect() {
    this.socket = new WebSocket(this.url);

    this.socket.addEventListener('open', () => {
      console.log(`WebSocket connected to ${this.url}`);
      if (this.options.onOpen) {
        this.options.onOpen();
      }
    });

    this.socket.addEventListener('close', (event) => {
      console.log(`WebSocket closed with code ${event.code}`);
      if (this.options.onClose) {
        this.options.onClose(event);
      }
    });

    this.socket.addEventListener('error', (event) => {
      console.error('WebSocket error:', event);
      if (this.options.onError) {
        this.options.onError(event);
      }
    });

    this.socket.addEventListener('message', (event) => {
      const response = JSON.parse(event.data);

      if (response.id && this.requests[response.id]) {
        this.requests[response.id](response.data);
        delete this.requests[response.id];
      }
    });
  }

  sendRequest(data, callback) {
    this.requestId++;
    this.requests[this.requestId] = callback;

    const request = {
      id: this.requestId,
      data: data,
    };

    this.socket.send(JSON.stringify(request));
  }

  close() {
    this.socket.close();
  }
}

//
我們向 WebSocketRequest 建構函式中傳遞了一個可選的 options 物件,其中包含了可選的事件處理程式。這樣,我們可以在 WebSocket 例項發生開啟、關閉、錯誤和接收訊息等事件時,觸發相應的處理程式。

//同時,我們新增了 close 方法來關閉 WebSocket 連線。這將在應用程式退出或需要斷開連線時非常有用。


//在使用時,你可以選擇傳遞任意數量的處理程式到 options 物件中,以便監聽各種事件。你還可以在建構函式中呼叫 connect 方法,以便在初始化時自動連線 WebSocket。

const
url = 'ws://your-websocket-server-url'; const socketRequest = new WebSocketRequest(url, { onOpen: () => { console.log('WebSocket opened'); }, onClose: (event) => { console.log(`WebSocket closed with code ${event.code}`); }, onError: (event) => { console.error('WebSocket error:', event); }, }); // 傳送請求 const requestData = { message: 'Hello, server!' }; socketRequest.sendRequest(requestData, (response) => { console.log('Response:', response); }); // 關閉 WebSocket 連線 socketRequest.close();

相關文章