zoukankan      html  css  js  c++  java
  • ws请求定时

    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);
          };
        },
  • 相关阅读:
    ATmega328P定时器详解
    成员指针与mem_fn
    引用传参与reference_wrapper
    定位new表达式与显式调用析构函数
    模板参数的“右值引用”是转发引用
    C++生成随机数
    测量C++程序运行时间
    Snmp扫描-snmpwalk、snmpcheck
    操作系统识别-python、nmap
    服务扫描-dmitry、nmap、amap和服务识别
  • 原文地址:https://www.cnblogs.com/supermanYU/p/15819006.html
Copyright © 2011-2022 走看看