Bläddra i källkod

1.websocket轮询

QuietShadow 3 år sedan
förälder
incheckning
882f1f2c10
1 ändrade filer med 15 tillägg och 13 borttagningar
  1. 15 13
      src/components/main.vue

+ 15 - 13
src/components/main.vue

@@ -1300,18 +1300,6 @@ export default {
         
                 // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
                 window.onbeforeunload = that.onbeforeunload
-                //每隔30秒钟发送一次心跳,避免websocket连接因超时而自动断开
-                  that.interval = window.setTimeout(function(){ // bug:每次都会触发init,用setInterval导致定时器不断叠加
-                      console.log('websoket 轮询');
-                      if(that.websocket !== null){
-                          if (that.websocket.readyState !== that.websocket.OPEN) {
-                              if (token) {
-                                  console.log('websocket again')
-                                  that.initWebSocket()
-                              }
-                          }
-                      }
-                  },30000);
                 } else {
                   alert('当前浏览器 Not support websocket');
                 }
@@ -1320,7 +1308,21 @@ export default {
                 console.log('WebSocket连接发生错误   状态码:' + this.websocket.readyState)
               },
               setOnopenMessage () {
-                console.log('WebSocket连接成功    状态码:' + this.websocket.readyState)
+                let that = this;
+                console.log('WebSocket连接成功    状态码:' + this.websocket.readyState);
+                //每隔30秒钟发送一次心跳,避免websocket连接因超时而自动断开
+                  that.interval = window.setTimeout(function(){ // bug:每次都会触发init,用setInterval导致定时器不断叠加
+                      console.log('websoket 轮询');
+                      if(that.websocket !== null){
+                          if (that.websocket.readyState == that.websocket.OPEN) {
+                                  console.log('websocket again')
+                                  // that.initWebSocket();
+                                  that.websocket.send('ping')
+                          } else {
+                            that.initWebSocket();
+                          }
+                      }
+                  },30000);
               },
               setOnmessageMessage (event) {
                 // 根据服务器推送的消息做自己的业务处理