java websocket中的ping-pong 机制

参考源码:html

https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/java/org/java_websocket/client/WebSocketClient.javajava

https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/java/org/java_websocket/AbstractWebSocket.javagit

https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/java/org/java_websocket/WebSocket.javagithub

https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/java/org/java_websocket/WebSocketImpl.javaweb

https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/java/org/java_websocket/drafts/Draft_6455.javawebsocket

 文章参考:网络

注: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

相关文章
相关标签/搜索