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>
相关推荐
u0111026754 小时前
Vue 3 统一右侧编辑面板:布局、滚动与底部操作区设计
javascript·vue.js·ecmascript
change_fate4 小时前
Vue 3 Composable 函数指南
前端·javascript·vue.js
tryCbest4 小时前
Vue3——第 9 篇:组件通信全攻略(下)——Provide / Inject 与事件总线
前端·javascript·vue.js
lichenyang4534 小时前
技术穿刺怎么做?以企业知识库问答为例,验证风险、方案和投入
前端·后端
PedroQue994 小时前
uni-app x工程化实战:从页面堆到可维护架构
前端·uni-app
开开心心_Every4 小时前
免费压缩软件WinRAR无弹窗、广告干扰
java·开发语言·前端·spring·智能手机·word·winrar
特立独行的猫A4 小时前
用仓颉语言写桌面应用:cj-tauri 框架与 AI 笔记软件 cjnote 实战
前端
syagain_zsx4 小时前
WebSocket 教程:websocketpp 写 echo 服务端
linux·网络·c++·websocket·网络协议·工具库
特立独行的猫A5 小时前
我为什么推荐用仓颉语言的cj-tauri 写桌面应用(附 cjnote 最小的markdown笔记AI软件)
前端
纸片人5 小时前
牛一越界,大屏 3 秒飞到它身边:我用真实卫星数据 + Three.js 做了个 3D 智慧牧场
前端