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

websocket在vue2中的封裝使用方式

 更新時間:2024年08月09日 10:17:14   作者:子恒吃西瓜  
這篇文章主要介紹了websocket在vue2中的封裝使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

websocket在vue2中的封裝使用

先說需求: 頁面中有websocket連接,進入的時候發(fā)送參數(shù)到后端,后端發(fā)送消息, 離開頁面時發(fā)送參數(shù)至后端,后端停止發(fā)送消息,不得斷開連接, 下一次進入時頁面時不用再次連接。

實現(xiàn)思路

  • 因為是全局連接一個websocket,所以這里采用單例模式
  • 也是因為封裝的原因,頁面中肯定是直接拿不到onmessage中返回的數(shù)據(jù), 所以這里采用發(fā)布訂閱模式來做

完整代碼在最后,不想看我廢話的可以直接扒拉了

步驟

步驟就是: 連接,頁面發(fā)送消息,接收消息,over ~

  • 首先定義連接websocket的方法
export default class SocketService {
    constructor(url){
        this.url = url
    },
    connect() {
        //判斷瀏覽器是否支持websocket
        if (!window.WebSocket) {
          return console.log("您的瀏覽器不支持WebSocket");
        }
        url,
	   //連接websocket
        this.ws = new WebSocket(this.url);
        //監(jiān)聽websocket各種狀態(tài)
        this.ws.onopen = () => {};
        this.ws.onclose = () => {};
        this.ws.onerror = () => {};
        this.ws.onmessage = (e) => {};
    }
}
  • 我們先讓socket連接上叭
export default class SocketService {
    constructor(url, againConnect = true){
        this.url = url
        this.againConnect = againConnect;
    },
      ws = null;         // 和服務端連接的socket對象
      url;               //地址
      againConnect;      //標識斷開是否重連
      connected = false; // 標識是否連接成功
      sendRetryCount = 0; // 記錄重試的次數(shù)
      connectRetryCount = 0; // 重新連接嘗試的次數(shù)
    connect() {
        //判斷瀏覽器是否支持websocket
        if (!window.WebSocket) {
          return console.log("您的瀏覽器不支持WebSocket");
        }
        url,
	   //連接websocket
        this.ws = new WebSocket(this.url);
        //監(jiān)聽websocket各種狀態(tài)
        this.ws.onopen = () => {
            //連接上后所有標識清零
            this.connected = true;
            this.connectRetryCount = 0;
        };
        this.ws.onclose = () => {
            //連接關閉
            this.connected = false;
            this.connectRetryCount++;
            if (this.againConnect) {
                //重連
                setTimeout(() => {
                  this.connect();
                }, 500 * this.connectRetryCount);
              } else {
                //不重連的操作
                 sessionStorage.clear();
                 localStorage.clear();
                 message.error("登錄超時");
                 router.push("/");
              }
        };
        this.ws.onerror = () => {
            //連接失敗
              this.connected = false;
              this.connectRetryCount++;
              if (this.againConnect) {
                setTimeout(() => {
                  this.connect();
                }, 500 * this.connectRetryCount);
              }
        };
        this.ws.onmessage = (e) => {
            console.log(e)
        };
    },
    unSubscribe() {}
    send(){
        //發(fā)送消息的方法
    }
}

那么我們要怎么給后端發(fā)送消息呢,發(fā)送了消息之后我們又該怎樣才能在頁面中接收到消息呢?

subscribeList = {}; //記載回調函數(shù)
idList = [];
send(data, callback) {
    //判斷此時有沒有ws
    if (!this.ws) {
      this.connect();
      this.send(data, callback);
    } else {
      // 判斷此時此刻有沒有連接成功
      if (this.connected) {
        this.sendRetryCount = 0;
        this.ws.send(JSON.stringify(data));
        if (data.type === "sub") {
          //存儲id
          this.idList.push(data.id);
          //存儲回調函數(shù),
          if (!this.subscribeList[data.id]) {
            this.subscribeList[data.id] = [callback];
          } else {
            this.subscribeList[data.id].push(callback);
          }
        }
      } else {
        this.sendRetryCount++;
        setTimeout(() => {
          this.send(data, callback);
        }, this.sendRetryCount * 500);
      }
    }
  }

connect(){
    ......
    this.ws.onmessage = (e) => {
      let { payload, requestId, type } = JSON.parse(e.data);
      if (type === "error") {
        console.log("出錯了");
      }
      if (this.subscribeList[requestId]) {
        if (type === "complete") {
          console.log("完成了");
        } else if (type === "result") {
          this.subscribeList[requestId].forEach((item) =>
            item.call(this, payload)
          );
        }
      }
    };
}
//銷毀回調函數(shù)
  unSubscribe() {
    //停止消息發(fā)送
    this.idList.forEach((item) => {
      this.send({ id: item, type: "unsub" });
      delete this.subscribeList[item];
    });
    this.idList = [];
 }

1.在send方法中接收一個回調函數(shù)

  • sub標識發(fā)送消息, unsub標識停止發(fā)送消息
  • id為事件的標識符

2.在message中調用

現(xiàn)在解決了頁面中接收消息的問題,那么怎么保證離開頁面,回到頁面,使用的是同一個websocket呢,如果實例化這個類的話,那么每次進入都會實例化SocketService,

instance = null;
static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService(false);
    }
    return this.instance;
 }

1.es6的class中有取值函數(shù)和存值函數(shù), 具體使用請看這里:

2.Class 的基本語法 - ES6 教程 - 網(wǎng)道

  • 使用getter,來拿取class中的instance,拿取的時候設置攔截該行為,判斷instance有沒有值,沒有值就實例化SocketService給instance,返回instance,

頁面中使用方式

import SocketService from "@/websocket/websocket";
mounted() {
    this.ws = SocketService.Instance;
    this.ws.send(
      {
        id: "11111",
        topic: "/xxx/xxx",
        parameter: {},
        type: "sub",
      },
      this.Callback
    );
}
destroyed() {
    this.ws.unSubscribe();
},
methods:{
    Callback(data) {
          console.log(data);
    },
}

看到這里了,不妨給個小心心叭

在vue中的封裝

export default class SocketService {
  constructor(againConnect = true, url) {
    this.url = url;
    this.againConnect = againConnect;
  }
  instance = null;  //頁面中使用的SocketService實例
  ws = null; // 和服務端連接的socket對象
  url; //地址
  againConnect;     //斷開是否重連
  connected = false; // 標識是否連接成功
  sendRetryCount = 0; // 記錄重試的次數(shù)
  connectRetryCount = 0; // 重新連接嘗試的次數(shù)
    
  //單例模式保證只有一個SocketService實例
  static get Instance() {
    if (!this.instance) {
        this.url = '......'
      this.instance = new SocketService(false, url);
    }
    return this.instance;
  }
  //  定義連接服務器的方法
  connect() {
    // 這里判斷你的瀏覽器支不支持websocket
    if (!window.WebSocket) {
      return console.log("您的瀏覽器不支持WebSocket");
    }
    this.ws = new WebSocket(this.url);
    //連接上了
    this.ws.onopen = () => {
      this.connected = true;
      // 重置重新連接的次數(shù)
      this.connectRetryCount = 0;
    };
      //連接關閉了,設置標識值為false,
    this.ws.onclose = () => {
      this.connected = false;
      this.connectRetryCount++;
      if (this.againConnect) {
        setTimeout(() => {
          this.connect();
        }, 500 * this.connectRetryCount);
      } else {
        sessionStorage.clear();
        localStorage.clear();
        message.error("登錄超時");
        router.push("/");
      }
    };
    this.ws.onerror = () => {
      console.log("socket連接失敗");
      this.connected = false;
      this.connectRetryCount++;
      if (this.againConnect) {
        setTimeout(() => {
          this.connect();
        }, 500 * this.connectRetryCount);
      }
    };
    this.ws.onmessage = (e) => {
      let { payload, requestId } = JSON.parse(e.data);
      if (this.subscribeList[requestId]) {
          this.subscribeList[requestId].forEach((item) =>
            item.call(this, payload)
          );
        }
    };
  }

  //銷毀回調函數(shù)
  unSubscribe() {
    //停止消息發(fā)送
    this.idList.forEach((item) => {
      this.send({ id: item, type: "unsub" });
      delete this.subscribeList[item];
    });
    this.idList = [];
  }
  subscribeList = {}; //記載回調函數(shù)
  idList = [];
  // 發(fā)送數(shù)據(jù)的方法
  send(data, callback) {
    //判斷此時有沒有ws
    if (!this.ws) {
      this.connect();
      this.send(data, callback);
    } else {
      // 判斷此時此刻有沒有連接成功
      if (this.connected) {
        this.sendRetryCount = 0;
        this.ws.send(JSON.stringify(data));

        if (data.type === "sub") {
          //存儲id
          this.idList.push(data.id);
          //存儲回調函數(shù),
          if (!this.subscribeList[data.id]) {
            this.subscribeList[data.id] = [callback];
          } else {
            this.subscribeList[data.id].push(callback);
          }
        }
      } else {
        this.sendRetryCount++;
        setTimeout(() => {
          this.send(data, callback);
        }, this.sendRetryCount * 500);
      }
    }
  }
}

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • vue調用高德地圖實例代碼

    vue調用高德地圖實例代碼

    本篇文章主要介紹了vue調用高德地圖實例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • vue實現(xiàn)全選、反選功能

    vue實現(xiàn)全選、反選功能

    這篇文章主要為大家詳細介紹了vue實現(xiàn)全選、反選功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • vue開發(fā)中數(shù)據(jù)更新但視圖不刷新的解決方法

    vue開發(fā)中數(shù)據(jù)更新但視圖不刷新的解決方法

    在開發(fā)中我們處理數(shù)據(jù)時會遇到數(shù)據(jù)更新了,但視圖并沒有更新,這種情況往往是數(shù)據(jù)嵌套層數(shù)過多導致的問題,下面這篇文章主要給大家介紹了關于vue開發(fā)中數(shù)據(jù)更新但視圖不刷新的解決方法,需要的朋友可以參考下
    2022-11-11
  • vue響應式更新機制及不使用框架實現(xiàn)簡單的數(shù)據(jù)雙向綁定問題

    vue響應式更新機制及不使用框架實現(xiàn)簡單的數(shù)據(jù)雙向綁定問題

    vue是一款具有響應式更新機制的框架,既可以實現(xiàn)單向數(shù)據(jù)流也可以實現(xiàn)數(shù)據(jù)的雙向綁定。這篇文章主要介紹了vue響應式更新機制及不使用框架實現(xiàn)簡單的數(shù)據(jù)雙向綁定問題,需要的朋友可以參考下
    2019-06-06
  • Vue百度地圖maker標注的添加和刪除方式

    Vue百度地圖maker標注的添加和刪除方式

    這篇文章主要介紹了Vue百度地圖maker標注的添加和刪除方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • Vue 計算屬性 computed

    Vue 計算屬性 computed

    這篇文章主要介紹了Vue 計算屬性 computed,一般情況下屬性都是放到data中的,但是有些屬性可能是需要經過一些邏輯計算后才能得出來,那么我們可以把這類屬性變成計算屬性,下面我們來看看具體實例,需要的朋友可以參考一下
    2021-10-10
  • vue中如何動態(tài)添加樣式

    vue中如何動態(tài)添加樣式

    這篇文章主要介紹了vue中如何動態(tài)添加樣式問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • 一文搞懂Vue里的過渡和動畫

    一文搞懂Vue里的過渡和動畫

    在Vue中,過渡和動畫是一種用于在組件之間添加平滑過渡效果和動畫效果的高級用法,Vue提供了一些內置的過渡和動畫功能,同時也支持自定義過渡和動畫效果,本文就給大家介紹一些Vue中過渡和動畫的高級用法,需要的朋友可以參考下
    2023-06-06
  • Vue中使用正則表達式進行文本匹配和處理的方法小結

    Vue中使用正則表達式進行文本匹配和處理的方法小結

    正則表達式在Vue中具有廣泛的應用場景,包括文本匹配和處理、表單驗證等,通過本文的介紹和示例,希望讀者能更好地理解和應用正則表達式在Vue中的使用方法,感興趣的朋友一起看看吧
    2023-11-11
  • vue實現(xiàn)組件值的累加

    vue實現(xiàn)組件值的累加

    這篇文章主要為大家詳細介紹了vue實現(xiàn)組件值的累加,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-09-09

最新評論

东源县| 漳平市| 太仆寺旗| 延安市| 苏州市| 东莞市| 大埔县| 通城县| 潞城市| 色达县| 宁武县| 焉耆| 尚志市| 大足县| 宜川县| 盱眙县| 鲜城| 临邑县| 商水县| 元氏县| 克拉玛依市| 中西区| 揭东县| 平度市| 全南县| 开化县| 安丘市| 江门市| 松阳县| 化德县| 习水县| 丰镇市| 通榆县| 牡丹江市| 苏尼特右旗| 金川县| 绵竹市| 龙胜| 江阴市| 济阳县| 英超|