java socket ping_java websocket中的ping-pong 机制

参考源码:

文章参考:

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

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

来源:oschina

链接:https://my.oschina.net/u/4349408/blog/3264305

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值