理解WebSocket心跳及重連機制(五)

理解WebSocket心跳及重連機制javascript

    在使用websocket的過程當中,有時候會遇到網絡斷開的狀況,可是在網絡斷開的時候服務器端並無觸發onclose的事件。這樣會有:服務器會繼續向客戶端發送多餘的連接,而且這些數據還會丟失。因此就須要一種機制來檢測客戶端和服務端是否處於正常的連接狀態。所以就有了websocket的心跳了。還有心跳,說明還活着,沒有心跳說明已經掛掉了。html

1. 爲何叫心跳包呢?
它就像心跳同樣每隔固定的時間發一次,來告訴服務器,我還活着。java

2. 心跳機制是?
心跳機制是每隔一段時間會向服務器發送一個數據包,告訴服務器本身還活着,同時客戶端會確認服務器端是否還活着,若是還活着的話,就會回傳一個數據包給客戶端來肯定服務器端也還活着,不然的話,有多是網絡斷開鏈接了。須要重連~web

那麼須要怎麼去實現它呢?以下全部代碼:後端

<html>
<head>
  <meta charset="utf-8">
  <title>WebSocket Demo</title>
</head>
<body>
  <script type="text/javascript">
    // var ws = new WebSocket("wss://echo.websocket.org");
    /*
    ws.onerror = function(e) {
      console.log('已關閉');
    };
    ws.onopen = function(e) {
      console.log('握手成功');
      ws.send('123456789');
    }
    ws.onclose = function() {
      console.log('已關閉');
    }
    ws.onmessage = function(e) {
      console.log('收到消息');
      console.log(e);
    }
    */
    
    var lockReconnect = false;//避免重複鏈接
    var wsUrl = "wss://echo.websocket.org";
    var ws;
    var tt;
    function createWebSocket() {
      try {
        ws = new WebSocket(wsUrl);
        init();
      } catch(e) {
        console.log('catch');
        reconnect(wsUrl);
      }
    }
    function init() {
      ws.onclose = function () {
        console.log('連接關閉');
        reconnect(wsUrl);
      };
      ws.onerror = function() {
        console.log('發生異常了');
        reconnect(wsUrl);
      };
      ws.onopen = function () {
        //心跳檢測重置
        heartCheck.start();
      };
      ws.onmessage = function (event) {
        //拿到任何消息都說明當前鏈接是正常的
        console.log('接收到消息');
        heartCheck.start();
      }
    }
    function reconnect(url) {
      if(lockReconnect) {
        return;
      };
      lockReconnect = true;
      //沒鏈接上會一直重連,設置延遲避免請求過多
      tt && clearTimeout(tt);
      tt = setTimeout(function () {
        createWebSocket(url);
        lockReconnect = false;
      }, 4000);
    }
    //心跳檢測
    var heartCheck = {
      timeout: 3000,
      timeoutObj: null,
      serverTimeoutObj: null,
      start: function(){
        console.log('start');
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function(){
          //這裏發送一個心跳,後端收到後,返回一個心跳消息,
          console.log('55555');
          ws.send("123456789");
          self.serverTimeoutObj = setTimeout(function() {
            console.log(111);
            console.log(ws);
            ws.close();
            // createWebSocket();
          }, self.timeout);

        }, this.timeout)
      }
    }
    createWebSocket(wsUrl);
  </script>
</body>
</html>

具體的思路以下:
1. 第一步頁面初始化,先調用createWebSocket函數,目的是建立一個websocket的方法:new WebSocket(wsUrl);所以封裝成函數內以下代碼:瀏覽器

function createWebSocket() {
  try {
    ws = new WebSocket(wsUrl);
    init();
  } catch(e) {
    console.log('catch');
    reconnect(wsUrl);
  }
}

2. 第二步調用init方法,該方法內把一些監聽事件封裝以下:服務器

function init() {
  ws.onclose = function () {
    console.log('連接關閉');
    reconnect(wsUrl);
  };
  ws.onerror = function() {
    console.log('發生異常了');
    reconnect(wsUrl);
  };
  ws.onopen = function () {
    //心跳檢測重置
    heartCheck.start();
  };
  ws.onmessage = function (event) {
    //拿到任何消息都說明當前鏈接是正常的
    console.log('接收到消息');
    heartCheck.start();
  }
}

3. 如上第二步,當網絡斷開的時候,會先調用onerror,onclose事件能夠監聽到,會調用reconnect方法進行重連操做。正常的狀況下,是先調用
onopen方法的,當接收到數據時,會被onmessage事件監聽到。websocket

4. 重連操做 reconnect代碼以下:網絡

var lockReconnect = false;//避免重複鏈接
function reconnect(url) {
  if(lockReconnect) {
    return;
  };
  lockReconnect = true;
  //沒鏈接上會一直重連,設置延遲避免請求過多
  tt && clearTimeout(tt);
  tt = setTimeout(function () {
    createWebSocket(url);
    lockReconnect = false;
  }, 4000);
}

如上代碼,若是網絡斷開的話,會執行reconnect方法,使用了一個定時器,4秒後會從新建立一個新的websocket連接,從新調用createWebSocket函數,
從新會執行及發送數據給服務器端。socket

5. 最後一步就是實現心跳檢測的代碼:以下:

//心跳檢測
var heartCheck = {
  timeout: 3000,
  timeoutObj: null,
  serverTimeoutObj: null,
  start: function(){
    console.log('start');
    var self = this;
    this.timeoutObj && clearTimeout(this.timeoutObj);
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
    this.timeoutObj = setTimeout(function(){
      //這裏發送一個心跳,後端收到後,返回一個心跳消息,
      //onmessage拿到返回的心跳就說明鏈接正常
      console.log('55555');
      ws.send("123456789");
      self.serverTimeoutObj = setTimeout(function() {
        console.log(111);
        console.log(ws);
        ws.close();
        // createWebSocket();
      }, self.timeout);

    }, this.timeout)
  }
}

實現心跳檢測的思路是:每隔一段固定的時間,向服務器端發送一個ping數據,若是在正常的狀況下,服務器會返回一個pong給客戶端,若是客戶端經過onmessage事件能監聽到的話,說明請求正常,這裏咱們使用了一個定時器,每隔3秒的狀況下,若是是網絡斷開的狀況下,在指定的時間內服務器端並無返回心跳響應消息,所以服務器端斷開了,所以這個時候咱們使用ws.close關閉鏈接,在一段時間後(在不一樣的瀏覽器下,時間是不同的,firefox響應更快),能夠經過 onclose事件監聽到。所以在onclose事件內,咱們能夠調用 reconnect事件進行重連操做。

相關文章
相關標籤/搜索