最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

記錄一次websocket封裝的過程

 更新時(shí)間:2020年11月23日 10:54:35   作者:大明的IT筆記  
這篇文章主要介紹了記錄一次websocket封裝的過程,幫助大家更好的理解和封裝websocket,感興趣的朋友可以了解下

在一個(gè)應(yīng)用中,websocket一般都是以單例形式存在的,即在整個(gè)應(yīng)用中,websocket實(shí)例始終保持唯一。但有時(shí)我們要用到websocket實(shí)例的時(shí)候,可能websocket還沒實(shí)例化,所以要做成異步的形式來獲取實(shí)例。

一、封裝。先創(chuàng)建 socket.ts 文件

import EventEmitter from 'events'; // 這里用到了 events 包
const ee = new EventEmitter();
class Ws {
 private wsUrl: string = '';
 private socket: WebSocket | undefined; // socket實(shí)例
 private lockReconnect: boolean = false; // 重連鎖
 private timeout: NodeJS.Timeout | undefined;

 // 初始化socket,一般在應(yīng)用啟動時(shí)初始化一次就好了,或者需要更換wsUrl
 public init(wsUrl: string) {
  this.wsUrl = wsUrl;
  this.createWebSocket();
 }

 // 獲取socket實(shí)例
 public getInstance(): Promise<WebSocket> {
  return new Promise((resolve, reject) => {
   if (this.socket) {
    resolve(this.socket);
   } else {
    ee.on('socket', (state: string) => {
     if (state === 'success') {
      resolve(this.socket);
     } else {
      reject();
     }
    });
   }
  });
 }

 // 創(chuàng)建socket
 private createWebSocket() {
  try {
   console.log('websocket 開始鏈接');
   const socket = new WebSocket(this.wsUrl);
   socket.addEventListener('close', () => {
    console.log('websocket 鏈接關(guān)閉');
    this.socket = undefined;
    this.reconnect();
   });
   socket.addEventListener('error', () => {
    console.log('websocket 發(fā)生異常了');
    this.socket = undefined;
    this.reconnect();
   });
   socket.addEventListener('open', () => {
    // 可在此進(jìn)行心跳檢測
    // this.heartCheck.start();
    console.log('websocket open');
    this.socket = socket;
    ee.emit('socket', 'success');
   });
   socket.addEventListener('message', (event) => {
    console.log('websocket 接收到消息', event);
   });
  } catch (e) {
   console.log('socket catch error', e);
   this.reconnect();
  }
 }

 // 重連
 private reconnect() {
  if (this.lockReconnect) {
   return;
  }
  console.log('websocket 正在重新連接');
  this.lockReconnect = true;
  //沒連接上會一直重連,設(shè)置延遲避免請求過多
  this.timeout && clearTimeout(this.timeout);
  this.timeout = setTimeout(() => {
   this.createWebSocket();
   this.lockReconnect = false;
  }, 5000);
 }
}

export default new Ws();

二、引入并使用

import socket from '@/utils/ws';

socket
 .getInstance()
 .then((ws) => {
   // 這里的 ws 就是實(shí)例化后的 websocket,可以直接使用 websocket 原生 api
  console.log('getInstance ws', ws);
  ws.addEventListener('message', (event) => {
    console.log('ws 接收到消息', event);
   });
 })
 .catch(() => {});

以上就是記錄一次websocket封裝的過程的詳細(xì)內(nèi)容,更多關(guān)于websocket封裝的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

高邮市| 和硕县| 宜川县| 嘉黎县| 玛沁县| 洪雅县| 乐陵市| 南宫市| 冕宁县| 建阳市| 红原县| 和硕县| 黄浦区| 成武县| 巩留县| 交口县| 彭州市| 乌拉特前旗| 巴彦县| 堆龙德庆县| 漠河县| 武胜县| 云龙县| 化隆| 亳州市| 贵州省| 广灵县| 营口市| 新兴县| 罗甸县| 古浪县| 麦盖提县| 林西县| 图片| 景谷| 长汀县| 安达市| 莒南县| 石台县| 晋中市| 吴忠市|