前端WebSocket封裝

場(chǎng)景1: 只有單個(gè)長鏈接,不要求保活

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();

調(diào)用方法:

import WebSocketClass from '@/services/webSocket';
var ws = WebSocketClass;
console.log(ws.getMessage());

關(guān)閉方法:

import WebSocketClass from '@/services/webSocket';
var ws = WebSocketClass;
ws.close();

場(chǎng)景2: 多個(gè)長鏈接共存

如果還是需要單例調(diào)用的話,直接用上面單個(gè)模式創(chuàng)建,有幾個(gè)創(chuàng)建幾個(gè),如果不需要保證單例的話:

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;

調(diào)用方式:

import WebSocketClass from '@/services/webSocket';
var ws = new WebSocketClass('ws://xxxxx');
console.log(ws.getMessage());

關(guān)閉:這種情況就無法跨域關(guān)閉了,只能在哪里開的在哪里關(guān),不然是關(guān)不了的,拿不到創(chuàng)建的時(shí)候的ws長鏈接對(duì)象。

保活

?;畹脑?->心跳,前端每隔一段時(shí)間發(fā)送一段約定好的message給后端,后端收到后返回一段約定好的message給前端,如果多久沒收到前端就調(diào)用重連方法進(jìn)行重連。

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() {
    // 心跳機(jī)制的時(shí)間可以自己與后端約定
    this.pingPong = 'ping'; // ws的心跳機(jī)制狀態(tài)值
    this.pingInterval = setInterval(() => {
      if (this.ws.readyState === 1) {
        // 檢查ws為鏈接狀態(tài) 才可發(fā)送
        this.ws.send('ping'); // 客戶端發(fā)送ping
      }
    }, 10000);
    this.pongInterval = setInterval(() => {
      if (this.pingPong === 'ping') {
        this.closeHandle('pingPong沒有改變?yōu)閜ong'); // 沒有返回pong 重啟webSocket
      }
      // 重置為ping 若下一次 ping 發(fā)送失敗 或者pong返回失敗(pingPong不會(huì)改成pong),將重啟
      console.log('返回pong');
      this.pingPong = 'ping';
    }, 20000);
  }

  closeHandle(e = 'err') {
    // 因?yàn)閣ebSocket并不穩(wěn)定,規(guī)定只能手動(dòng)關(guān)閉(調(diào)closeMyself方法),否則就重連
    if (this.status !== 'close') {
      console.log(`斷開,重連websocket`, e);
      if (this.pingInterval !== undefined && this.pongInterval !== undefined) {
        // 清除定時(shí)器
        clearInterval(this.pingInterval);
        clearInterval(this.pongInterval);
      }
      this.connect(); // 重連
    } else {
      console.log(`websocket手動(dòng)關(guān)閉,或者正在連接`);
    }
  }

  getMessage() {
    this.ws.onmessage = e => {
      if (e.data === 'pong') {
        this.pingPong = 'pong'; // 服務(wù)器端返回pong,修改pingPong的狀態(tài)
      } 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();


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

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

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