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

Vue WebSocket简单应用 ws

webSocket应用

<template><div></div>
</template><script>
import { getToken } from "@/utils/auth";
export default {data() {return {url: "",Socket: null, //socket对象lockReconnect: false, //锁定拒绝重连close: false, //是否关闭timer: null, //定时器//   reconnectNum: 3, //重连次数};},created() {this.connect();},beforeDestroy() {// 页面销毁时关闭连接this.lockReconnect = true;this.close = true;if (this.Socket) {this.Socket.close(); //关闭链接this.Socket = null;}},methods: {// 消息推送WebSocketconnect() {try {if ("WebSocket" in window) {let isPro = process.env.NODE_ENV === "production"; // 正式环境let urlHead = "ws://";if (location.protocol === "https:") {urlHead = "wss://";}this.url = isPro? urlHead +location.host +"/websocket/alarm/": "ws://10.19.11.111:11111/websocket/alarm/";// process.env.VUE_APP_WEVSOCKET_PATH;this.Socket = new WebSocket(this.url + getToken());}console.log("正在连接...");this.initEventHandle();} catch (err) {console.log(err, "失败");}},// 监听连接状态+取数据initEventHandle() {this.Socket.onclose = (e) => {this.clearTimer(); //清除定时器this.reconnect(); //定时重连console.log(e.target, "连接关闭!" + new Date().toLocaleString());};this.Socket.onerror = (e) => {this.reconnect(); //定时重连console.log(e.target, "连接错误!");};this.Socket.onopen = (e) => {this.heartCheck(); //心跳检测重置console.log(e.target, "连接成功!" + new Date().toLocaleString());};// 接收数据this.Socket.onmessage = (e) => {if (e.data != "pong") {let data = JSON.parse(e.data);console.log("数据转换", data);}};},// 清除定时器clearTimer() {clearInterval(this.timer);this.timer = null;},// 断开然后定时重连reconnect() {if (this.lockReconnect || this.close) return;//   if (this.reconnectNum >= 3) return; //最多重连三次this.lockReconnect = true;setTimeout(() => {//没连接上会一直重连,设置延迟避免请求过多// this.reconnectNum++;this.connect();this.lockReconnect = false;}, 500);},// 发送心跳检测heartCheck() {this.clearTimer();this.timer = setInterval(() => {// 三十秒钟发一次心跳包this.Socket.send("ping");// console.log("--ping--");}, 30000);},},
};
</script>
<style scoped></style>
http://www.lryc.cn/news/532458.html

相关文章:

  • 快速单机部署ollama v0.5.7 +openwebui(免去网络环境干扰)
  • 【华为OD-E卷 - 114 找最小数 100分(python、java、c++、js、c)】
  • 快速搭建GPU环境 | docker、k8s中使用gpu
  • VSCode设置——通过ctrl+鼠标滚动改变字体大小(新版本的vs)
  • 【kafka实战】06 kafkaTemplate java代码使用示例
  • Java 23新特性
  • bat脚本实现自动化漏洞挖掘
  • [创业之路-285]:《产品开发管理-方法.流程.工具 》-1- IPD的功能列表以及导入步骤
  • Redis命令:列表模糊删除详解
  • Day36-【13003】短文,数组的行主序方式,矩阵的压缩存储,对称、三角、稀疏矩阵和三元组线性表,广义表求长度、深度、表头、表尾等
  • 大数据sql查询速度慢有哪些原因
  • 文件 I/O 和序列化
  • 机器学习中的关键概念:通过SKlearn的MNIST实验深入理解
  • HELLOCTF反序列化靶场全解
  • 十二、Docker Compose 部署 SpringCloudAlibaba 微服务
  • VUE之插槽
  • 4. Go结构体使用
  • 版本控制的重要性及 Git 入门
  • [NKU]C++安装环境 VScode
  • deepseek本地部署
  • 网络编程day1
  • QFileDialog::getOpenFileName(this,“文件对话框“,“.“,“c++ files(*.cpp);;“); 文件对话框显示乱码
  • 绿联NAS安装cpolar内网穿透工具实现无公网IP远程访问教程
  • C++学习——缺省参数、重载函数、引用
  • web-JSON Web Token-CTFHub
  • langchain教程-11.RAG管道/多轮对话RAG
  • Postgresql的三种备份方式_postgresql备份
  • WebAssembly:前后端开发的未来利器
  • Mac下使用brew安装go 以及遇到的问题
  • 【Leetcode 每日一题】47. 全排列 II