前端WebSocket封裝


參考:https://www.jianshu.com/p/a4eacaf8de17

 

 

一、只有單個長鏈接,不要求保活

class WebSocketClass {
  constructor() {
    this.instance = null;
    this.connect();
  }
  static getInstance() {
    if (!this.instance) {
      this.instance = new WebSocketClass();
    }
    return this.instance;
  }

  connect() {
    this.ws = new WebSocket('ws://xxxxxx');
    this.ws.onopen = e => {
      this.status = 'open';
      console.log(`${name}連接成功`, e);
    };
  }

  getMessage() {
    this.ws.onmessage = e => {
      console.log(e.data);
      return e.data;
    };
  }

   close() {
    this.ws.send('close');
    this.ws.close();
    console.log('close');
  }
}

export default new WebSocketClass();

二、多個長鏈接共存

class WebSocketClass {
  constructor(name) {
    this.connect(name);
  }

  connect(name) {
    this.ws = new WebSocket(name);
    this.ws.onopen = e => {
      this.status = 'open';
      console.log(`${name}連接成功`, e);
    };
  }

  getMessage() {
    this.ws.onmessage = e => {
      console.log(e.data);
      return e.data;
    };
  }

  close() {
    this.ws.send('close');
    this.ws.close();
    console.log('close');
  }
}

export default WebSocketClass;

關閉:這種情況就無法跨頁面關閉了,只能在哪里開的在哪里關,不然是關不了的,拿不到創建的時候的ws長鏈接對象。

三、保活

保活的原理-->心跳,前端每隔一段時間發送一段約定好的message給后端,后端收到后返回一段約定好的message給前端,如果多久沒收到前端就調用重連方法進行重連。

import { message } from 'antd';

class WebSocketClass {
  constructor() {
    this.instance = null;
    this.connect();
  }
  static getInstance() {
    if (!this.instance) {
      this.instance = new WebSocketClass();
    }
    return this.instance;
  }

  connect() {
    this.ws = new WebSocket('ws://xxxx');
    this.ws.onopen = e => {
      this.status = 'open';
      message.info('連接成功');
      console.log(`連接成功`, e);
      this.heartCheck();
      this.getMessage();
    };
  }

  heartCheck() {
    // 心跳機制的時間可以自己與后端約定
    this.pingPong = 'ping'; // ws的心跳機制狀態值
    this.pingInterval = setInterval(() => {
      if (this.ws.readyState === 1) {
        // 檢查ws為鏈接狀態 才可發送
        this.ws.send('ping'); // 客戶端發送ping
      }
    }, 10000);
    this.pongInterval = setInterval(() => {
      if (this.pingPong === 'ping') {
        this.closeHandle('pingPong沒有改變為pong'); // 沒有返回pong 重啟webSocket
      }
      // 重置為ping 若下一次 ping 發送失敗 或者pong返回失敗(pingPong不會改成pong),將重啟
      console.log('返回pong');
      this.pingPong = 'ping';
    }, 20000);
  }

  closeHandle(e = 'err') {
    // 因為webSocket並不穩定,規定只能手動關閉(調closeMyself方法),否則就重連
    if (this.status !== 'close') {
      console.log(`斷開,重連websocket`, e);
      if (this.pingInterval !== undefined && this.pongInterval !== undefined) {
        // 清除定時器
        clearInterval(this.pingInterval);
        clearInterval(this.pongInterval);
      }
      this.connect(); // 重連
    } else {
      console.log(`websocket手動關閉,或者正在連接`);
    }
  }

  getMessage() {
    this.ws.onmessage = e => {
      if (e.data === 'pong') {
        this.pingPong = 'pong'; // 服務器端返回pong,修改pingPong的狀態
      } else {
        message.info(e.data);
      }
      console.log(e.data);
      return e.data;
    };
  }

  close() {
    clearInterval(this.pingInterval);
    clearInterval(this.pongInterval);
    this.status = 'close';
    this.ws.send('close');
    this.ws.close();
    message.info('已斷開連接');
    console.log('close');
  }
}

export default new WebSocketClass();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM