前端WebSocket封裝

場景1: 只有單個長連接,不要求保活

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

複製代碼

調用方法:前端

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

關閉方法:web

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

場景2: 多個長連接共存

若是仍是須要單例調用的話,直接用上面單個模式建立,有幾個建立幾個,若是不須要保證單例的話:後端

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;
複製代碼

調用方式:跨域

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

關閉:這種狀況就沒法跨域關閉了,只能在哪裏開的在哪裏關,否則是關不了的,拿不到建立的時候的ws長連接對象。bash

保活

保活的原理-->心跳,前端每隔一段時間發送一段約定好的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:xxxxx');
    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();


複製代碼
相關文章
相關標籤/搜索