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>
相关推荐
青皮桔29 分钟前
CSS实现百分比水柱图
前端·css
影子信息34 分钟前
vue 前端动态导入文件 import.meta.glob
前端·javascript·vue.js
青阳流月35 分钟前
1.vue权衡的艺术
前端·vue.js·开源
RunsenLIu37 分钟前
基于Vue.js + Node.js + MySQL实现的图书销售管理系统
vue.js·mysql·node.js
样子201839 分钟前
Vue3 之dialog弹框简单制作
前端·javascript·vue.js·前端框架·ecmascript
kevin_水滴石穿40 分钟前
Vue 中报错 TypeError: crypto$2.getRandomValues is not a function
前端·javascript·vue.js
翻滚吧键盘41 分钟前
vue文本插值
javascript·vue.js·ecmascript
华子w90892585942 分钟前
基于 SpringBoot+Vue.js+ElementUI 的 “花开富贵“ 花园管理系统设计与实现7000字论文
vue.js·spring boot·elementui
2501_915909062 小时前
调试 WebView 旧资源缓存问题:一次从偶发到复现的实战经历
websocket·网络协议·tcp/ip·http·网络安全·https·udp
孤水寒月2 小时前
给自己网站增加一个免费的AI助手,纯HTML
前端·人工智能·html