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

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

 更新時(shí)間:2023年03月08日 11:45:29   作者:梓恒  
這篇文章主要為大家介紹了一文詳解websocket在vue2中的封裝使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

websocket在vue2中的封裝使用

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

實(shí)現(xiàn)思路:

  • 因?yàn)槭侨诌B接一個(gè)websocket,所以這里采用單例模式
  • 也是因?yàn)榉庋b的原因,頁面中肯定是直接拿不到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;         // 和服務(wù)端連接的socket對象
       url;               //地址
       againConnect;      //標(biāo)識斷開是否重連
       connected = false; // 標(biāo)識是否連接成功
       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 = () => {
             //連接上后所有標(biāo)識清零
             this.connected = true;
             this.connectRetryCount = 0;
         };
         this.ws.onclose = () => {
             //連接關(guān)閉
             this.connected = false;
             this.connectRetryCount++;
             if (this.againConnect) {
                 //重連
                 setTimeout(() => {
                   this.connect();
                 }, 500 * this.connectRetryCount);
               } else {
                 //不重連的操作
                  sessionStorage.clear();
                  localStorage.clear();
                  message.error("登錄超時(shí)");
                  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方法中接收一個(gè)回調(diào)函數(shù),

在message中調(diào)用,

 subscribeList = {}; //記載回調(diào)函數(shù)
 idList = [];
 send(data, callback) {
     //判斷此時(shí)有沒有ws
     if (!this.ws) {
       this.connect();
       this.send(data, callback);
     } else {
       // 判斷此時(shí)此刻有沒有連接成功
       if (this.connected) {
         this.sendRetryCount = 0;
         this.ws.send(JSON.stringify(data));
         if (data.type === "sub") {
           //存儲id
           this.idList.push(data.id);
           //存儲回調(diào)函數(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)
           );
         }
       }
     };
 }
 //銷毀回調(diào)函數(shù)
   unSubscribe() {
     //停止消息發(fā)送
     this.idList.forEach((item) => {
       this.send({ id: item, type: "unsub" });
       delete this.subscribeList[item];
     });
     this.idList = [];
  }
  • sub標(biāo)識發(fā)送消息, unsub標(biāo)識停止發(fā)送消息
  • id為事件的標(biāo)識符

現(xiàn)在解決了頁面中接收消息的問題,那么怎么保證離開頁面,回到頁面,使用的是同一個(gè)websocket呢,如果實(shí)例化這個(gè)類的話,那么每次進(jìn)入都會實(shí)例化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,拿取的時(shí)候設(shè)置攔截該行為,判斷instance有沒有值,沒有值就實(shí)例化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);
     },
 }

看到這里了,不妨給個(gè)小心心叭

在vue中的封裝

 export default class SocketService {
   constructor(againConnect = true, url) {
     this.url = url;
     this.againConnect = againConnect;
   }
   instance = null;  //頁面中使用的SocketService實(shí)例
   ws = null; // 和服務(wù)端連接的socket對象
   url; //地址
   againConnect;     //斷開是否重連
   connected = false; // 標(biāo)識是否連接成功
   sendRetryCount = 0; // 記錄重試的次數(shù)
   connectRetryCount = 0; // 重新連接嘗試的次數(shù)
   //單例模式保證只有一個(gè)SocketService實(shí)例
   static get Instance() {
     if (!this.instance) {
         this.url = '......'
       this.instance = new SocketService(false, url);
     }
     return this.instance;
   }
   //  定義連接服務(wù)器的方法
   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;
     };
       //連接關(guān)閉了,設(shè)置標(biāo)識值為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("登錄超時(shí)");
         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)
           );
         }
     };
   }
   //銷毀回調(diào)函數(shù)
   unSubscribe() {
     //停止消息發(fā)送
     this.idList.forEach((item) => {
       this.send({ id: item, type: "unsub" });
       delete this.subscribeList[item];
     });
     this.idList = [];
   }
   subscribeList = {}; //記載回調(diào)函數(shù)
   idList = [];
   // 發(fā)送數(shù)據(jù)的方法
   send(data, callback) {
     //判斷此時(shí)有沒有ws
     if (!this.ws) {
       this.connect();
       this.send(data, callback);
     } else {
       // 判斷此時(shí)此刻有沒有連接成功
       if (this.connected) {
         this.sendRetryCount = 0;
         this.ws.send(JSON.stringify(data));
         if (data.type === "sub") {
           //存儲id
           this.idList.push(data.id);
           //存儲回調(diào)函數(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中的封裝使用的詳細(xì)內(nèi)容,更多關(guān)于vue2封裝websocket的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • vue3:setup的兩個(gè)注意點(diǎn)詳解

    vue3:setup的兩個(gè)注意點(diǎn)詳解

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

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

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

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

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

    Vue實(shí)現(xiàn)點(diǎn)擊按鈕復(fù)制文本內(nèi)容的例子

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

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

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

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

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

    vue 點(diǎn)擊其他區(qū)域關(guān)閉自定義div操作

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

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

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

    詳解Vue-Router的安裝與使用

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

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

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

最新評論