当前位置: 首页 > news >正文

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.lryc.cn/news/259819.html

相关文章:

  • 018 OpenCV 人脸检测
  • Etcd实战(一)-部署etcd集群
  • Python绘制一个简单的圣诞树
  • 【CANoe】CANoe中使用RS232
  • Springboot内置Tomcat线程数优化
  • vue+django 开发环境跨域前后端联调配置
  • Apache+mod_jk模块代理Tomcat容器
  • Nginx访问FTP服务器文件的时效性/安全校验
  • 【VSCode】自定义配置
  • SpringBoot整合Kafka (一)
  • 随机分词与tokenizer(BPE->BBPE->Wordpiece->Unigram->sentencepiece->bytepiece)
  • 成都工业学院Web技术基础(WEB)实验四:CSS3布局应用
  • TikTok科技趋势:平台如何引领数字社交革命?
  • 【上海大学数字逻辑实验报告】六、时序电路
  • docker版zerotier-planet服务端搭建
  • 【Spring教程28】Spring框架实战:从零开始学习SpringMVC 之 请求与请求参数详解
  • node.js和浏览器之间的区别
  • 【python并发任务的几种方式】
  • 使用ROS模板基于ECS和RDS创建WordPress环境
  • 龙迅LT2611UXC 双PORT LVDS转HDMI(2.0)+音频
  • websocket和SSE通信示例(无需安装任何插件)
  • 计算机网络(三)
  • HttpURLConnection OOM问题记录
  • WT588F02B单片机语音芯片在磁疗仪中的应用介绍
  • 深度学习——第5章 神经网络基础知识
  • 微信网页授权步骤说明
  • linux bash shell变量操作符 —— 筑梦之路
  • 2.61【Python生成器与迭代器】
  • devecho stuido npm 失败
  • postgreSql逻辑复制常用语句汇总和说明