vue webSocket

发布于:2025-04-17 ⋅ 阅读:(36) ⋅ 点赞:(0)


一、vue2 + webSocket

webSocket.js

export default {
  data() {
    return {
      websock: null, // 建立的连接,存websocket实例化的
      lockReconnect: false, // 是否真正建立连接
      timeout: 1000 * 5, // 5秒一次心跳
      timeoutObj: null, // 心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时
      wsId: Math.ceil(Math.random() * 9999) + 1000, // uuid随机数(1000-9999)
      notification: null, // 进度提示
    };
  },
  created() {
    // 页面刚进入时开启长连接
    this.initWebSocket();
  },
  destroyed() {
    // 页面销毁时关闭长连接
    // this.websocketclose();
    this.websock.close();
    this.lockReconnect = true;
    if (this.timeoutnum)
      clearTimeout(this.timeoutnum);
    if (this.timeoutObj)
      clearTimeout(this.timeoutObj);
    if (this.serverTimeoutObj)
      clearTimeout(this.serverTimeoutObj);
  },
  methods: {
    // 建立连接,初始化weosocket
    initWebSocket() {
      // 当前浏览器Location对象
      const nowLocation = window.location;
      // 协议 => http、https
      const protocol = nowLocation.protocol;
      // host => ip:port
      const host = nowLocation.host;
      // 后台地址,前面的ws不动,后面是后台地址,我是本地运行的所以填的本地,自行更改。再后面webSocket是后端的接口地址,uuid_test002是参数
      const wsuri = ((protocol.startsWith('https')) ? 'wss://' : 'ws://') + host + this.staticUrl + ((protocol.startsWith('https')) ? '/wssApi' : '/wsApi') + "/webSocket/" + this.wsId;
      this.websock = new WebSocket(wsuri); // 建立连接
      this.websock.onopen = this.websocketonopen; // 连接成功
      this.websock.onerror = this.websocketonerror; // 连接错误
      this.websock.onmessage = this.websocketonmessage; // 接收信息
      this.websock.onclose = this.websocketclose; // 连接关闭
    },
    // 链接成功时执行的方法
    websocketonopen() {
      this.websocketsend("heartbeat"); // 连接成功事件
      this.start(); // 开启心跳
    },
    // 连接失败事件
    websocketonerror(e) {
      console.log("WebSocket连接发生错误");
      this.reconnect(); // 重连
    },
    // 连接关闭事件
    websocketclose(e) {
      this.websock.close();
      this.reconnect(); // 重连
    },
    // 接收服务器推送的信息
    websocketonmessage(event) {
      const data = JSON.parse(event.data)
      switch (data.message) {
        case 'generateDataPacket':
          this.$showLoadMsg(data.data)
          break
        case 'importPackage-progress': // 进度通知
          if (!this.notification) {
            this.notification = this.$notify({
              title: '提示',
              message: '导入进度:' + data.data,
              duration: 0,
              // offset: 100,
              customClass: 'notify_top',
            });
          } else {
            this.notification.message = '导入进度:' + data.data
          }
          break
        case 'importPackage-success': // 成功
          this.$message.success(data.data)
          this.notification.close()
          this.notification = null
          break
        case 'importPackage-over': // 异常
          this.$message.error(data.data)
          break
        case 'importPackage-repeat': // 有重复数据需要展示
          this.repeatDataVisible = true
          data.data.id = data.data.newData.id
          data.data.loadRow = false
          this.repeatDataList.push(data.data)
          break
      }
      this.reset(); // 收到服务器信息,心跳重置
    },
    // 向服务器发送信息
    websocketsend(msg) {
      this.websock.send(msg);
    },
    // 重新连接
    reconnect() {
      var that = this;
      // 判断链接状态,true就是链接,false是断开,这里如果是链接状态就不继续执行了,跳出来。
      if (that.lockReconnect) {
        return;
      }
      // 把链接状态改为true
      that.lockReconnect = true;
      // 没连接上会一直重连,设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum);
      that.timeoutnum = setTimeout(function () {
        that.initWebSocket(); // 初始化新连接
        that.lockReconnect = false; // 把链接状态改为false
      }, 5000);
    },
    // 重置心跳
    reset() {
      var that = this;
      // 清除时间
      clearTimeout(that.timeoutObj);
      clearTimeout(that.serverTimeoutObj);
      // 重启心跳
      that.start();
    },
    // 开启心跳
    start() {
      var self = this;
      // 有延迟时间的就清除掉
      self.timeoutObj && clearTimeout(self.timeoutObj);
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      // 从新创建计时器
      self.timeoutObj = setTimeout(function () {
        // 这里发送一个心跳,后端收到后,返回一个心跳消息
        if (self.websock.readyState == 1) {
          // 如果连接正常发送信息到后台
          self.websock.send("heartbeat");
        } else {
          // 否则重连
          self.reconnect();
        }
        self.serverTimeoutObj = setTimeout(function () {
          self.websock.close(); // 超时关闭
        }, self.timeout);
      }, self.timeout);
    },
  },
};

vue2

import webSocketMixin from '@/components/common/mixins/webSocket.js'
export default {
  mixins: [webSocketMixin],
  data() {
    return {
      repeatDataVisible: false,
      repeatDataList: [],
    }
  },
  mounted() {
    this.initList()
  },
  methods: {
    // 下载
    leadingOutDataPacket(row) {
      window.location.href = `${this.staticUrl}/globalApi/export?path=${encodeURIComponent(row.path)}`
    },
    // 导入数据
    leadingInDataPacket(row) {
      this.$confirm('&emsp;&emsp;导入数据会进行较长时间,期间系统将无法正常使用,请耐心等待。<br /><br />&emsp;&emsp;确定要导入数据吗?', '警告!', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        let param = {
          operate: 'importPackage',
          data: {
            path: row.path
          }
        }
        param = JSON.stringify(param)
        this.websock.send(param);
      }).catch(() => {
        this.$message.info('已取消')
      })
    },
  },
}

二、vue3 + webSocket + ts

webSocket.ts

代码

vue3

代码

网站公告

今日签到

点亮在社区的每一天
去签到