欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

一文詳解websocket在vue2中的封裝使用

 更新時間:2023年03月08日 11:45:29   作者:梓恒  
這篇文章主要為大家介紹了一文詳解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ā)送了消息之后我們又該怎樣才能在頁面中接收到消息呢?

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

在message中調用,

 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 = [];
  }
  • sub標識發(fā)送消息, unsub標識停止發(fā)送消息
  • id為事件的標識符

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

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

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

 instance = null;
 static get Instance() {
     if (!this.instance) {
       this.instance = new SocketService(false);
     }
     return this.instance;
  }
  • 使用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);
       }
     }
   }
 }

以上就是一文詳解websocket在vue2中的封裝使用的詳細內容,更多關于vue2封裝websocket的資料請關注腳本之家其它相關文章!

相關文章

  • vue3:setup的兩個注意點詳解

    vue3:setup的兩個注意點詳解

    這篇文章主要介紹了vue3.0中setup的兩個注意點,本文通過兩種用法給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-10-10
  • vue雙向數(shù)據(jù)綁定指令v-model的用法

    vue雙向數(shù)據(jù)綁定指令v-model的用法

    這篇文章主要介紹了vue雙向數(shù)據(jù)綁定指令v-model的用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • vue組件命名和props命名代碼詳解

    vue組件命名和props命名代碼詳解

    在本篇內容里小編給大家講的是關于vue組件命名和props命名的相關知識點內容,有興趣的朋友們可以學習下。
    2019-09-09
  • Vue實現(xiàn)點擊按鈕復制文本內容的例子

    Vue實現(xiàn)點擊按鈕復制文本內容的例子

    今天小編就為大家分享一篇Vue實現(xiàn)點擊按鈕復制文本內容的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • Vue.js實現(xiàn)表格渲染的方法

    Vue.js實現(xiàn)表格渲染的方法

    今天小編就為大家分享一篇對Vue.js實現(xiàn)表格渲染的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-09-09
  • vue使用showdown并實現(xiàn)代碼區(qū)域高亮的示例代碼

    vue使用showdown并實現(xiàn)代碼區(qū)域高亮的示例代碼

    這篇文章主要介紹了vue使用showdown并實現(xiàn)代碼區(qū)域高亮的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-10-10
  • vue 點擊其他區(qū)域關閉自定義div操作

    vue 點擊其他區(qū)域關閉自定義div操作

    這篇文章主要介紹了vue 點擊其他區(qū)域關閉自定義div操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • vue中v-model和.sync修飾符的區(qū)別

    vue中v-model和.sync修飾符的區(qū)別

    在平時開發(fā)是經(jīng)常用到一些父子組件通信,經(jīng)常用到props、vuex等等,下面這篇文章主要給大家介紹了關于vue中v-model和.sync修飾符區(qū)別的相關資料,需要的朋友可以參考下
    2022-06-06
  • 詳解Vue-Router的安裝與使用

    詳解Vue-Router的安裝與使用

    Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,讓構建單頁面應用變得易如反掌。本文介紹下Vue Router的安裝與使用
    2021-06-06
  • 利用Vue3實現(xiàn)可復制表格的方法詳解

    利用Vue3實現(xiàn)可復制表格的方法詳解

    表格是前端非常常用的一個控件,本文主要為大家介紹了Vue3如何實現(xiàn)一個簡易的可以復制的表格,文中的示例代碼講解詳細,需要的可以參考一下
    2022-12-12

最新評論