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>
相关推荐
学以智用4 分钟前
Vue3 + Vue Router 4 完整示例(可直接运行)
前端·vue.js
程序员小李白6 分钟前
vue2基本语法详细解析(2.7条件渲染)
开发语言·前端·javascript
SuperEugene6 分钟前
Vue3 项目目录结构规范:按业务域划分,新人快速上手|项目规范篇
前端·javascript·vue.js
卤蛋fg67 分钟前
vue表单vxe-from配置渲染日期范围选择器的用法
vue.js
悟空瞎说8 分钟前
# 10年前端血坑:Canvas drawImage画不出图?90%的人栽在这几步
前端
qibmz11 分钟前
新电脑安装 nvm 卡住?无需修改配置文件,一行命令完美解决!
前端
遗憾随她而去.22 分钟前
高德地图自定义点标记: SVG vs HTML+CSS两种方案
前端·css
陕西小伙伴网络科技有限公司23 分钟前
kettle单转换实现分页查询
开发语言·前端·javascript
踩着两条虫25 分钟前
低代码 + AI,到底是生产力革命,还是下一代“技术债务”?
前端·人工智能·低代码
终端鹿38 分钟前
深度解析 WebSocket DevTools 插件
网络·websocket·网络协议