vue全局使用webSokcet

ops/2024/10/22 12:10:42/
// App.vue
export default {data() {return {// socket参数socket: null,timeout: 10 * 1000, // 45秒一次心跳timeoutObj: null, // 心跳心跳倒计时serverTimeoutObj: null, // 心跳倒计时timeoutnum: null, // 断开 重连倒计时lockReconnect: false, // 防止websocket: null};},mounted() {this.initWebSocket(userId); // userId为socket链接的参数},methods:{initWebSocket(supplierId) {// WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于httpslet wsUrl = `wss://192.168.1.33/rest/supplier-api/wss/websocket/${userId}`;this.websocket = new WebSocket(wsUrl);this.websocket.onopen = this.websocketonopen;this.websocket.onerror = this.websocketonerror;this.websocket.onmessage = this.setOnmessageMessage;this.websocket.onclose = this.websocketclose;// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。// window.onbeforeunload = that.onbeforeunload},start() {console.log('start');//清除延时器this.timeoutObj && clearTimeout(this.timeoutObj);this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);this.timeoutObj = setTimeout(() => {if (this.websocket && this.websocket.readyState == 1) {this.websocket.send('heartBath');//发送消息,服务端返回信息,即表示连接良好,可以在socket的onmessage事件重置心跳机制函数} else {this.reconnect();}//定义一个延时器等待服务器响应,若超时,则关闭连接,重新请求server建立socket连接this.serverTimeoutObj = setTimeout(() => {this.websocket.close();}, this.timeout)}, this.timeout)},reset() { // 重置心跳// 清除时间clearTimeout(this.timeoutObj);clearTimeout(this.serverTimeoutObj);// 重启心跳this.start();},// 重新连接reconnect() {if (this.lockReconnect) returnthis.lockReconnect = true;//没连接上会一直重连,设置延迟避免请求过多this.timeoutnum && clearTimeout(this.timeoutnum);this.timeoutnum = setTimeout(() => {this.initWebSocket();this.lockReconnect = false;}, 5000)},async setOnmessageMessage(event) {console.log(event.data, '获得消息');this.reset();// 自定义全局监听事件window.dispatchEvent(new CustomEvent('onmessageWS', {detail: {data: event.data}}))// //发现消息进入    开始处理前端触发逻辑// if (event.data === 'success' || event.data === 'heartBath') return},websocketonopen() {//开启心跳this.start();console.log("WebSocket连接成功!!!"+new Date()+"----"+this.websocket.readyState);},websocketonerror(e) {                console.log("WebSocket连接发生错误" + e);              },websocketclose(e) {this.websocket.close();clearTimeout(this.timeoutObj);clearTimeout(this.serverTimeoutObj);console.log("WebSocket连接关闭");},websocketsend(messsage) {that.websocket.send(messsage)},closeWebSocket() { // 关闭websocketthat.websocket.close()},}

其他页面监听数据

mounted () {// 添加socket通知监听window.addEventListener('onmessageWS', this.getSocketData)
},
methods: {// 收到消息处理getSocketData (res) {if (res.detail.data === 'success' || res.detail.data === 'heartBath') return// ...业务处理},
}

其他页面放松信息就需要创建一个global.js

// global.js
export default {ws: {},setWs: function(newWs) {this.ws = newWs}
}

挂载到全局main.js

import global from './utils/global';
Vue.prototype.$global = global

修改app.vue

export default {data() {return {// socket参数socket: null,timeout: 10 * 1000, // 45秒一次心跳timeoutObj: null, // 心跳心跳倒计时serverTimeoutObj: null, // 心跳倒计时timeoutnum: null, // 断开 重连倒计时lockReconnect: false, // 防止websocket: null,};},mounted() {setTimeout(()=>{this.initWebSocket();},1500)},methods: {initWebSocket() {this.websocket = new WebSocket(`/socket?token=${window.localStorage.getItem("token")}`);this.$global.setWs(this.websocket)// this.websocket.onopen = this.websocketonopen;this.websocket.onerror = this.websocketonerror;this.websocket.onmessage = this.setOnmessageMessage;},start() {console.log("start");//清除延时器this.timeoutObj && clearTimeout(this.timeoutObj);this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);this.timeoutObj = setTimeout(() => {if (this.websocket && this.websocket.readyState == 1) {// this.websocket.send("heartBath"); //发送消息,服务端返回信息,即表示连接良好,可以在socket的onmessage事件重置心跳机制函数} else {this.reconnect();}//定义一个延时器等待服务器响应,若超时,则关闭连接,重新请求server建立socket连接this.serverTimeoutObj = setTimeout(() => {this.websocket.close();}, this.timeout);}, this.timeout);},reset() {// 重置心跳// 清除时间clearTimeout(this.timeoutObj);clearTimeout(this.serverTimeoutObj);// 重启心跳this.start();},// 重新连接reconnect() {if (this.lockReconnect) return;this.lockReconnect = true;//没连接上会一直重连,设置延迟避免请求过多this.timeoutnum && clearTimeout(this.timeoutnum);this.timeoutnum = setTimeout(() => {this.initWebSocket();this.lockReconnect = false;}, 5000);},async setOnmessageMessage(event) {console.log(event.data, "获得消息");// this.reset();// 自定义全局监听事件window.dispatchEvent(new CustomEvent("onmessageWS", {detail: {data: event.data,},}));// //发现消息进入    开始处理前端触发逻辑// if (event.data === 'success' || event.data === 'heartBath') return},websocketonopen() {//开启心跳this.start();console.log("WebSocket连接成功!!!" + new Date() + "----" + this.websocket.readyState);},websocketonerror(e) {console.log("WebSocket连接发生错误" + e);},websocketclose(e) {this.websocket.close();clearTimeout(this.timeoutObj);clearTimeout(this.serverTimeoutObj);console.log("WebSocket连接关闭");},websocketsend(messsage) {this.websocket.send(messsage);},closeWebSocket() {// 关闭websocketthis.websocket.close();},},
};

其他页面发送send时

this.$global.ws.send(JSON.stringify(obj))


http://www.ppmy.cn/ops/127560.html

相关文章

三品PLM系统解决方案赋能航空制造企业 研发管理升级赢得市场主动

航空航天,作为人类探索宇宙的先锋,不仅彰显科技的极致魅力,更是衡量一个国家在科技、经济和国防方面实力的重要标志。它体现人类对宇宙的好奇与追求,是国家综合实力的集中展现与证明。 据航空产业网数据,2023年我国航…

golang的协程

启动一个协程 使用go关键字启动一个新的协程时,就是并发地执行一个函数。换句话说,go关键字后面必须跟着一个可调用的函数(或者是一个匿名函数、闭包等)。 func sayHello() { fmt.Println("Hello, World!") } f…

Java爬虫:从入门到精通实战指南

在信息技术飞速发展的今天,数据已成为最宝贵的资源之一。Java作为一种成熟且功能强大的编程语言,不仅在企业级应用开发中占据主导地位,也成为了编写爬虫程序的理想选择。Java爬虫能够自动化地从网页或API中提取数据,为数据分析、机…

HttpURLConnection和OkHttp的特点

HttpURLConnection与OkHttp概述及个人倾向性分析 在Java和Android开发中,HttpURLConnection与OkHttp都是用于处理HTTP请求的库,它们在功能、性能、易用性等方面各有千秋。本文将详细阐述两者的特点,并结合个人使用经验,表达我对哪…

WSL2 构建Ubuntu系统-轻量级AI运行环境

环境:Win11 软件:WSL2 安装环境:Ubuntu 22.04 检查电脑是否开启虚拟化 打开:任务管理器->性能->CPU CPU 开启虚拟化(通常默认是开启的,如果没有开启需要BIOS开启) 虚拟化设置&#xff0…

Python GIF压缩工具实现详解:PIL的实践

在本文中,我们将详细分析一个使用Python开发的GIF压缩工具的实现。这个工具结合了wxPython的GUI框架和PIL(Python Imaging Library)的图像处理能力,提供了两种压缩方式:颜色深度压缩和帧数压缩。 C:\pythoncode\new\gifcompress.py 全部代码…

PostgreSQL的学习心得和知识总结(一百五十五)|[performance]优化期间将 WHERE 子句中的 IN VALUES 替换为 ANY

目录结构 注:提前言明 本文借鉴了以下博主、书籍或网站的内容,其列表如下: 1、参考书籍:《PostgreSQL数据库内核分析》 2、参考书籍:《数据库事务处理的艺术:事务管理与并发控制》 3、PostgreSQL数据库仓库…

正则化、交叉验证、

正则化 是机器学习中用来防止模型过拟合的一种技术。过拟合是指模型在训练数据上表现很好,但在新的、未见过的数据上表现不佳。正则化通过在损失函数中添加一个额外的项来实现,这个额外的项通常与模型的复杂度相关。下面是正则化项的作用和意义&#xf…