QQ交流群:110826636

java websocket中的ping-pong 机制

参考源码:

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

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

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

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

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

 文章参考:

注:websocket基于tcp协议,它在第一次连接时发起http请求,之后建立握手

在websocket中设置setConnectionLostTimeout参数,解释为:Setter for the interval checking for lost connections,意思是间隔检查连接是否丢失

整体是调用顺序为:onWebsocketOpen -》 startConnectionLostTimer -》 restartConnectionLostTimer-》 scheduleAtFixedRate -》 executeConnectionLostDetection

关键代码
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。

posted @ 2019-05-08 15:51  FourOne  阅读(7454)  评论(0编辑  收藏