参考源码:java
文章参考:socket
注:websocket基于tcp协议,它在第一次链接时发起http请求,以后创建握手tcp
在websocket中设置setConnectionLostTimeout参数,解释为:Setter for the interval checking for lost connections,意思是间隔检查链接是否丢失this
总体是调用顺序为:onWebsocketOpen -》 startConnectionLostTimer -》 restartConnectionLostTimer-》 scheduleAtFixedRate -》 executeConnectionLostDetectionspa
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。