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>
相关推荐
Alair‎4 分钟前
前端开发之环境配置
前端·react.js
谢尔登6 分钟前
Vue3底层原理——keep-alive
javascript·vue.js·ecmascript
Deca~9 分钟前
VueVirtualLazyTree-支持懒加载的虚拟树
前端·javascript·vue.js
爱上妖精的尾巴17 分钟前
7-11 WPS JS宏 对象的属性值为函数的写法与用法
前端·javascript·wps·js宏·jsa
zuozewei18 分钟前
零基础 | 使用LangChain框架实现ReAct Agent
前端·react.js·langchain
坠入暮云间x18 分钟前
React Native for OpenHarmony开发环境搭建指南(一)
前端·react native·开源
爱上妖精的尾巴21 分钟前
7-12 WPS JS宏 this、return用构造函数自定义类-1:对象内部函数,外部调用的写法
前端·javascript·wps·js宏·jsa
har01d27 分钟前
AI生成的 vue3 日历组件,显示农历与节日,日期可选择,年月可切换
前端·vue.js·节日
冲刺逆向33 分钟前
【js逆向案例六】创宇盾(加速乐)通杀模版
java·前端·javascript