ws请求定时
阅读原文时间:2023年07月09日阅读:6

heartChechInit() {

      const _this = this;

      // 设置统筹管理

      let heartCheck = {

        timer: 0, // 定时器名称

        _obj: null, // ws

        _callback: null, // 执行函数

        _time: 30000, // 心跳间隔

        // 启动函数

        init: function (wsObj, callback) {

          // console.log("init");

          this._obj = wsObj;

          callback && (this._callback = callback);

          this.sayHi();

        },

        sayHi: function () {

          // 执行心跳

          clearTimeout(this.timer);

          this.timer = setTimeout(() => {

            if (1 == this._obj.readyState) {

              this._obj.send(1); // 发送讯息

            }

          }, this._time);

        },

        clear: function (flag) {

          // 关闭

          // console.log("clear:" + this.timer);

          clearTimeout(this.timer);

        },

        onError: function () {

          // 出错

          // console.log("onError:", this.timer);

          this.clear();

          this._callback && this._callback();

        },

      };

      // 通讯地址

      let uri = `ws://${sessionStorage.getItem("heartCheckUrl")}/flow/notice/${

        _this.currentUserID

      }`;

      let ws = new WebSocket(uri);

      // 开始连接

      ws.onopen = (event) => {

        // console.log("ws onopen", event);

        MsgBegin && MsgBegin();

        heartCheck.init(ws, () => {

          console.log("reconnect…");

          ws = new WebSocket(uri);

        });

      };

      // 接收消息

      ws.onmessage = (event) => {

        // console.log("接收消息", event, ws);

        let reg = /[0-9]/;

        if (reg.test(event.data)) {

          _this.value = +event.data;

        } else {

          _this.value = 0;

        }

        heartCheck.sayHi();

      };

      // 连接关闭

      ws.onclose = (event) => {

        // console.log("ws close", event, ws);

        heartCheck.clear();

      };

      // 连接出错

      ws.onerror = (event) => {

        _this.value = 0;

        // console.log("ws error", event, ws);

        heartCheck.onError();

      };

      // 初始请求接收

      let MsgBegin = () => {

        ws.send(1);

      };

    },

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章