java websocket中的ping-pong 机制

北城以北 提交于 2020-11-19 05:18:50

参考源码:

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。

原文出处:https://www.cnblogs.com/RainbowInTheSky/p/10832366.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!