zoukankan      html  css  js  c++  java
  • websocket

    //websocket推送

    wsFn() {

      let that = this,
      baseInfo = that.$store.state.baseInfo,
      url = "";//websocket的url
      if("WebSocket" in window) {
        let ws = new WebSocket(url +  '传的字段''),
         sot = null;
        ws.keepalive = function() {
          let time = new Date().getTime();
          // 如果断网了,ws.send会无法发送消息出去。ws.bufferedAmount不会为0。
          if(ws.bufferedAmount === 0 && ws.readyState === 1) {
            let req = {
              "data": {
                //要传的数据

                ......
              }
            }
        ws.send(JSON.stringify(req));
      }
    }
    if(ws) {
      let reconnect = 0, //重连的时间
          reconnectMark = false; //是否重连过
      ws.onopen = function() {
        reconnect = 0;
        reconnectMark = false;
        if(ws.readyState === 1) { // 为1表示连接处于open状态
          ws.keepalive();
          ws.keepAliveTimer = setInterval(function() {
            ws.keepalive();
          }, 60000)
        }
      }
      ws.onmessage = function(evt) {
      console.log(555555555)
      let received_msg = JSON.parse(evt.data);
      if(received_msg.msgType == 0) {

        //如果此时已连接上,且可以发送信息
          console.log(222222)
          //要做的事情

          ......
      }
    }
    ws.onerror = function(e) {
      console.error('onerror');
    }
    ws.onclose = function() {
      console.log("onclose连接已关闭...");
      clearInterval(ws.keepAliveTimer);
      if(!reconnectMark) { // 如果没有重连过,进行重连。
        reconnect = new Date().getTime();
        reconnectMark = true;
      }
      let tempWs = ws; // 保存ws对象
      if(!window.navigator.onLine) {
        ws.close();
      } else {
        //非断网情况下
        if(new Date().getTime() - reconnect >= 5000) { // 5秒中重连,连不上就不连了
          ws.close();
          sot = setTimeout(function() {
            ws.close();
            that.wsFn();
            clearTimeout(sot);
          }, 60000)
        } else {
          ws = new WebSocket(url + '传的字段'');
          ws.onopen = tempWs.onopen;
          ws.onmessage = tempWs.onmessage;
          ws.onerror = tempWs.onerror;
          ws.onclose = tempWs.onclose;
          ws.keepalive = tempWs.keepalive;
        }
      }
    }
    }
    // 网络波动情况下,情况下导致webSocket的问题
    window.addEventListener("online", function() {
      clearTimeout(sot);
      ws.close();
      that.wsFn();
    }, true);
    window.addEventListener("offline", function() {
      ws.close();
    }, true);
    }
    }
    },

  • 相关阅读:
    python中特殊参数self的作用
    python中类的初始化案例
    python中类的调用
    Python--网络编程-----struct模块的字节数限制
    Python--网络编程-----解决粘包问题-简单版
    Python--网络编程-----粘包的底层原理分析
    Python--网络编程-----粘包现象
    Python--网络编程-----socket编程示例--模拟ssh远程执行命令
    pycharm下 os.system执行命令返回有中文乱码
    Python--网络编程-----socket编程示例--打电话--加上链接循环
  • 原文地址:https://www.cnblogs.com/sunflower-zy/p/8533804.html
Copyright © 2011-2022 走看看