參考源碼:html
文章參考:網絡
機制圖解:
注:websocket基於tcp協議,它在第一次鏈接時發起http請求,以後創建握手socket
在websocket中設置setConnectionLostTimeout參數,解釋爲:Setter for the interval checking for lost connections,意思是間隔檢查鏈接是否丟失tcp
總體是調用順序爲:onWebsocketOpen -》 startConnectionLostTimer -》 restartConnectionLostTimer-》 scheduleAtFixedRate -》 executeConnectionLostDetectionthis
關鍵代碼
this.connectionLostTimeout = TimeUnit.SECONDS.toNanos(connectionLostTimeout); if (this.connectionLostTimeout <= 0) { log.trace("Connection lost timer stopped"); cancelConnectionLostTimer(); return; }
long minimumPongTime = (long) (System.nanoTime() - ( connectionLostTimeout * 1.5 )); for( WebSocket conn : connections ) { executeConnectionLostDetection(conn, minimumPongTime); }
WebSocketImpl webSocketImpl = (WebSocketImpl) webSocket; if( webSocketImpl.getLastPong() < minimumPongTime ) { log.trace("Closing connection due to no pong received: {}", webSocketImpl); webSocketImpl.closeConnection( CloseFrame.ABNORMAL_CLOSE, "The connection was closed because the other endpoint did not respond with a pong in time. For more information check: https://github.com/TooTallNate/Java-WebSocket/wiki/Lost-connection-detection" ); } else { if( webSocketImpl.isOpen() ) { webSocketImpl.sendPing(); } else { log.trace("Trying to ping a non open connection: {}", webSocketImpl); } }
connectionLostTimeout在設置後會轉爲納秒時間, minimumPongTime爲當前納秒時間減去connectionLostTimeout的1.5倍,當最後一次Pong的時間小於minimumPongTime時產生close,即在間隔時間內未收到Pong響應關閉鏈接。若是正常則繼續發送ping,即調用sendPing。
在服務端收到ping的時候,當即下發pong,二者的容忍時間爲connectionLostTimeout是1.5倍,即設十秒的話就是容忍十五秒。當網絡發生異常時,二者狀況,服務端沒有收到ping亦或者客戶端沒有收到pong,觸發close。
原文出處:https://www.cnblogs.com/RainbowInTheSky/p/10832366.html