Vue項目中WebSocket封裝

WEBSOCKET

  • 封裝
  • 引入
  • 初始化
  • 使用

封裝

utils下建立WebSocketManager.js

class WebSocketManager {constructor() {this.url = null;this.websocket = null;this.isConnected = false;this.listeners = {onopen: [],onmessage: [],onclose: [],onerror: [],};this.reconnectionOptions = {enabled: true,maxAttempts: 5,delay: 3000,};this.reconnectionAttempts = 0;this.connecting = false;this.url = null;this.preventReconnect = false;// 添加Ping-Pong定時器this.pingInterval = null;this.websocketId = '';}initializeWebSocket(url) {sessionStorage.setItem('ws_url', url);if (!this.websocket ||this.websocket.readyState === WebSocket.CLOSED) {const websocketId = new Date().getTime();this.websocketId = websocketId;this.websocket = new WebSocket(url);this.url = url;this.preventReconnect = false; // 重置標志位this.websocket.onopen = (event) => {if (websocketId !== this.websocketId) {return}console.log('onopen', websocketId);this.isConnected = true;this.connecting = false;this.reconnectionAttempts = 0;this.fireListeners('onopen', event);this.websocket.send(`ping`);console.log('send registerEcmsServer');this.startPingPong();};this.websocket.onmessage = (event) => {if (websocketId !== this.websocketId) {return}console.log('onmessage', event.data);try {const jsonData = JSON.parse(event.data);this.fireListeners('onmessage', jsonData);} catch (e) {// console.error('onmessage-err', e);}};this.websocket.onclose = (event) => {console.log('onclose ', event);if (websocketId !== this.websocketId) {console.log('do xxx')return}this.stopPingPong();if (event.code !== 4000) {setTimeout(() => {console.log('reconnect ');this.reconnect();}, 2000);}};this.websocket.onerror = (error) => {if (websocketId !== this.websocketId) {return}console.log('onerror ', error);this.fireListeners('onerror', error);};} else {console.log('Soeket exists, no need to create it, 鏈接狀態:',  this.websocket.readyState === WebSocket.OPEN);}}close() {this.preventReconnect = true;this.reconnectionAttempts = 0;this.connecting = false;this.url = null;this.preventReconnect = false;this.isConnected = false;if (this.websocket) {this.websocket.close(4000);}}reconnect() {if (!this.url && sessionStorage.getItem('ws_url')) {return;}if (!this.preventReconnect && !this.connecting) {this.connecting = true;this.reconnectionAttempts++;setTimeout(() => {this.initializeWebSocket(this.url);}, this.reconnectionOptions.delay);}}send(message) {if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {this.websocket.send(message);}}addEventListener(eventType, callback) {if (this.listeners[eventType]) {this.listeners[eventType].push(callback);}}removeEventListener(eventType, callback) {if (this.listeners[eventType]) {const index = this.listeners[eventType].indexOf(callback);if (index !== -1) {this.listeners[eventType].splice(index, 1);}}}fireListeners(eventType, event) {this.listeners[eventType].forEach((callback) => {callback(event);});}startPingPong() {if (this.pingInterval) {clearInterval(this.pingInterval);}// 設置Ping間隔(ms)const pingInterval = 20 * 1000;this.pingInterval = setInterval(() => {if (this.websocket &&this.websocket.readyState === WebSocket.OPEN) {// 發送Ping消息this.websocket.send(`ping`);}}, pingInterval);}stopPingPong() {// 停止Ping-Pong定時器if (this.pingInterval) {clearInterval(this.pingInterval);this.pingInterval = null;}}
}const WebSocketManagerInstance = new WebSocketManager();export default WebSocketManagerInstance;

引入

在main.js中引入

import Vue from 'vue';
import Socket from '@/utils/WebSocketManager';
Vue.prototype.$socket = Socket;

初始化

const WS= 'ws://127.0.0.1:80/ws';
this.$socket.initializeWebSocket(WS);

使用

    mounted() {this.$socket.addEventListener('onmessage', this.handleWs);},beforeDestroy() {this.$socket.removeEventListener('onmessage', this.handleWs);},methods: {// 處理wshandleWs(e) {switch (e.method) {// 被動進入庭審case 'XXX':console.log('xxx')break;}},}

如有不足,請多指教,
未完待續,持續更新!
大家一起進步!

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/214104.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/214104.shtml
英文地址,請注明出處:http://en.pswp.cn/news/214104.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

QML如何與C++層進行信號槽通訊

//QML端為槽函數 //其中serial為C類的對象 //CSerial serial(暫且可以這么理解) QML: Connections{ target: serial onStringReceived:{ console.log("receive:"receiveString) } } //C端為信號 //C //C類…

kafka 常用命令【學習筆記】

Kafka 環境變量配置 export KAFKA_HOME/opt/cloudera/parcels/CDH-6.3.2-1.cdh6.3.2.p0.1605554/lib/kafka export PATH P A T H : PATH: PATH:KAFKA_HOME/bin 查看主題 ./kafka-topics.sh --list --zookeeper localhost:2181 創建主題 ./kafka-topics.sh --create --zook…

保研畢業論文查重率多少通過【保姆教程】

大家好,今天來聊聊保研畢業論文查重率多少通過,希望能給大家提供一點參考。 以下是針對論文重復率高的情況,提供一些修改建議和技巧: 保研畢業論文查重率多少通過 在保研過程中,畢業論文的查重率是衡量學術誠信和論文…

JAVA8新特性之函數式編程詳解

JAVA8新特性之函數式編程詳解 前言一、初步了解函數式接口二、 Lambda表達式2.1 概述2.2 lambda省略規則2.3 lambda省略常見實例2.4 lambda表達式與函數式接口 三、 Stream流3.1 stream流的定義3.2 Stream流的特點3.3 Stream流的三個步驟3.4 Stream 和 Collection 集合的區別&a…

【HarmonyOS開發】拖拽動畫的實現

動畫的原理是在一個時間段內,多次改變UI外觀,由于人眼會產生視覺暫留,所以最終看到的就是一個“連續”的動畫。UI的一次改變稱為一個動畫幀,對應一次屏幕刷新,而決定動畫流暢度的一個重要指標就是幀率FPS(F…

【帶頭學C++】----- 九、類和對象 ---- 9.12 C++之友元函數(9.12.1---12.4)

??????????????????????創做不易,麻煩點個關注???????????????????????? ??????????????????文末有驚喜!獻舞一支!???????????????????? 目錄 9.12…

TypeError: Cannot set properties of undefined (setting ‘xx‘)

在寫代碼中經常會遇到TypeError: Cannot set properties of undefined (setting ‘xx‘),這個問題。 一般出現的場景:在調用接口訪問后端數據時,前端渲染顯示空白,并報此錯。例如,我在調用高德地圖,輸入經…

五:爬蟲-數據解析之xpath解析

三:數據解析之xpath解析 1.xpath介紹: ? xpath是XML路徑語言,它可以用來確定xml文檔中的元素位置,通過元素路徑來完成對元素的查找,HTML就是XML的一種實現方式,所以xpath是一種非常強大的定位方式? XPa…

vue2 element-ui select下拉框 選擇傳遞多個參數

<el-select v-model"select" slot"prepend" placeholder"請選擇" change"searchPostFn($event,123)"> <el-option :label"item.ziDianShuJu" :value"{value:item.id, label:item.ziDianShuJu}" v-for&qu…

Ubuntu系統使用快速入門實踐(七)——軟件安裝與使用(5)

Ubuntu系統使用快速入門實踐系列文章 下面是Ubuntu系統使用系列文章的總鏈接&#xff0c;本人發表這個系列的文章鏈接均收錄于此 Ubuntu系統使用快速入門實踐系列文章總鏈接 下面是專欄地址&#xff1a; Ubuntu系統使用快速入門實踐系列文章專欄 文章目錄 Ubuntu系統使用快速…

crypto-js加密、解密與node Crypto加解密模塊的應用

前端用crypto-js實現加解密&#xff0c;node端用Crypto模塊&#xff0c;兩者想要相同結果的話&#xff0c;就要保持加密密鑰和加密算法一致。 crypto-js加密、解密 參考&#xff1a; 『crypto-js 加密和解密』 前端使用CryptoJS加密解密 // DES算法 import CryptoJS from cryp…

【unity】【WebRTC】從0開始創建一個Unity遠程媒體流app-構建可同步場景

【背景】 最近在研究遠程畫面&#xff0c;所以就實踐了一下。技術采用我認為比較合適的WebRTC。 這篇文章的基礎是我的另一篇博文&#xff0c;如果希望順利完成本篇操作&#xff0c;請先關注我后查詢我的如下博文&#xff1a; 【WebRTC】【Unity】Unity Web RTC1-Unity中簡單實…

Docker架構及常用的命令

一、初識Docker 1、 docker是一個快速交付應用、運行應用的技術&#xff0c;具備下列優勢&#xff1a; 可以將程序及其依賴、運行環境一起打包為一個鏡像&#xff0c;可以遷移到任意Linux操作系統運行時利用沙箱機制形成隔離容器&#xff0c;各個應用互不干擾啟動、移除都可以…

邊緣智能網關如何應對環境污染難題

隨著我國工業化、城鎮化的深入推進&#xff0c;包括大氣污染在內的環境污染防治壓力繼續加大。為應對環境污染防治難題&#xff0c;佰馬綜合邊緣計算、物聯網、智能感知等技術&#xff0c;基于邊緣智能網關打造環境污染實時監測、預警及智能干預方案&#xff0c;可應用于大氣保…

銀行數據分析入門篇:信用卡全生命周期分析,到底應該怎么做?

最近有朋友向我咨詢銀行信貸業務的數據分析&#xff0c;就看了很多案例&#xff0c;剛好看到一個信用卡全生命周期分析的案例&#xff0c;做得很詳細又通俗易懂&#xff0c;基本上可以直接復制套用&#xff0c;所以特地分享給大家。 本文主要分享作者整個分析作品的思路&#x…

Unity對象池

標題&#xff1a;Unity對象池技術詳解 一、引言 在Unity游戲開發中&#xff0c;我們經常需要創建大量的游戲對象&#xff0c;如子彈、敵人和道具等。然而&#xff0c;頻繁地創建和銷毀這些對象會消耗大量的系統資源&#xff0c;影響游戲的性能。為了解決這個問題&#xff0c;…

golang 使用 viper 加載配置文件 自動反序列化到結構

golang使用 viper 無需設置 mapstructure tag 根據配置文件后綴 自動返序列化到結構 解決結構有下劃線的字段解析不成功問題 viper 正常加載配置文件 golang viper 其中可以用來 查找、加載和反序列化JSON、TOML、YAML、HCL、INI、envfile和格式的配置文件 配置文件 test_to…

jdom利用純java技術對xml文檔進行解析、生成、序列化等各種操作

Jdom對xml文檔進行解析、生成、序列化等各種操作。 使用jdom之前&#xff0c;首先要導入jar包&#xff1a;jdom.jar 獲得根元素&#xff1a; //首先確定xml文件位置 String xmlPath "./src/ceshi/Test.xml"; //使用的解析器&#xff0c;這里表示默認的解…

KMP算法數組下標從0和數組下標從1開始

我在運用KMP時&#xff0c;總時會搞混如果數組下標為0時要如何用寫&#xff0c;下標為1時要如何寫。 當下標為0時kmp void kmp(int len) {//下標為0 時vector<int> f(n,-1);for(int i 1;i < len;i){ // 每次更新的是 下標i // 當第 i1不匹配是 跳到 f[i]的位置上&…

106.進程控制(結束、孤兒、僵尸進程)以及進程回收

目錄 結束進程 孤兒進程 僵尸進程 進程回收 wait() waitpid 進程控制是指在操作系統中對進程進行創建、終止、掛起、喚醒以及進程之間的同步、通信等操作的管理。 結束進程 exit() 和 _exit() 函數都用于終止一個進程&#xff0c;但它們之間有一些重要的區別&#xf…