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

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: {
    // 消息推送WebSocket
    connect() {
      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.kler.cn/a/534497.html

相关文章:

  • “AI隐患识别系统,安全多了道“智能护盾”
  • axios如何利用promise无痛刷新token
  • 【R语言】获取数据
  • DeepSeek R1技术报告关键解析(6/10):DeepSeek-R1 vs. OpenAI-o1-1217:性能对比分析
  • NeetCode刷题第21天(2025.2.4)
  • 在Mapbox GL JS中“line-pattern”的使用详解
  • openEuler系统添加静态路由的方法
  • 【华为OD-E卷 - 114 找最小数 100分(python、java、c++、js、c)】
  • 算法日记11:SC63(离散化)
  • 106,【6】 buuctf web [SUCTF 2019]CheckIn
  • Unity-向量运算及归一化
  • 单例设计模式(Java)
  • 传送带中大块煤识别数据集,使用yolo,coco,voc格式对1546张现场环境图片进行标注
  • Tailwind CSS v4.0 升级与 Astro 5.2 项目迁移记录
  • 开源AI智能名片2 + 1链动模式S2B2C商城小程序:内容价值创造与传播新引擎
  • Gauss高斯:建表语法,存储方式,OLTP和OLAP,系统时间,数组,分组(grouping set,rollup)
  • 6.PPT:魏女士-高新技术企业政策【19】
  • ES6 变量解构赋值总结
  • PostgreSQL 数据库模式基础操作
  • 蓝桥杯三国游戏(贪心)
  • 面对全球化的泼天流量,出海企业如何观测多地域网络质量?
  • ASP.NET Core中间件的概念及基本使用
  • SpringCloud速通教程
  • Vue3状态管理: Pinia使用技巧与最佳实践
  • Ubuntn24.04安装
  • windows-蓝牙驱动开发-蓝牙软件无线电开关函数原型