websocket

  refresh() {
      if (window.confirm('重置将清空已采集的数据,是否继续?')) {
        this.tableData = [];
        if (this.websock.readyState > 1) {
          this.websocketsend(JSON.stringify({ reset: true }));
        }
        window.location.href = '/';
      }
    },
    stop(status) {
      if (status) {
        this.isClose = false;
        this.websock.close();
      } else {
        this.initWebSocket();
      }
    },
    initWebSocket() {
      // 初始化weosocket
      const wsuri =
        process.env.NODE_ENV === 'production'
          ? 'ws://47.111.28.93:2000'
          : 'ws://10.0.1.78:2000';
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() {
      // 连接建立之后执行send方法发送数据
      if (this.isClose) {
        const actions = { reset: true };
        this.websocketsend(JSON.stringify(actions));
      }
    },
    websocketonerror() {
      // 连接建立失败重连
      this.initWebSocket();
    },
    websocketonmessage(e) {
      // 数据接收
      const redata = JSON.parse(e.data);
      console.log(redata);
      if (redata.code === 200) {
        this.tableData.push(...redata.data);
        this.number.violation = redata.count.violation;
        this.number.amount = redata.count.amount;
        this.number.shops = redata.count.shops;
        this.number.items = redata.count.items;
        this.isScrollTop && this.scrollBottom();
        this.$store.dispatch('set_collecting', true);
        this.$store.dispatch('set_number', {
          show: true,
          value: this.tableData.length
        });
      } else {
        this.$message.error(redata.message);
      }
    },
    websocketsend(Data) {
      // 数据发送
      console.log(Data);
      this.websock.send(Data);
    },
    websocketclose(e) {
      // 关闭
      console.log('断开连接', e);
    }

 

posted @ 2022-03-30 16:22  聂小恶  阅读(26)  评论(0编辑  收藏  举报