Newer
Older
Nanping_sponge_GCYPG / src / store / modules / websocket.js
@liyingjing liyingjing on 25 Oct 1 KB 工程预评估
const websocketStore = defineStore("websocket", {
  state: () => ({
    //推送消息
    data: {},
    webSocket: null,
    timer: null,
    hearbeat_interval: 1000 * 2,
    count: 0,
  }),
  actions: {
    initWebsocket(url) {
      var that = this;
      console.log("url", url);
      this.webSocket = new WebSocket(
        "wss://server1.wh-nf.cn:8132/patrol/websocket/" + url
      );
      this.webSocket.onopen = function () {
        console.log("通讯开始");
        this.timer && clearInterval(this.timer);
        this.timer = setInterval(() => {
          //   this.webSocket.send(
          //     JSON.stringify({
          //       token: Math.random(),
          //     })
          //   );
        }, this.hearbeat_interval);
      };
      this.webSocket.onmessage = function (e) {
        // console.log("收到的数据:", JSON.parse(e.data));
        that.count++;
        that.data = JSON.parse(e.data);
        // console.log(that.count);
      };
      this.webSocket.onerror = function () {
        console.log("通讯异常");
      };
      this.webSocket.onclose = function () {
        console.log("连接已断开");
        this.timer && clearInterval(this.timer);
      };
    },
  },
});

export default websocketStore;