1. 客户端写空闲4s发一次心跳
2. 服务端收到心跳回复
3. 服务端读空闲 (n个4s) + x未收到心跳,close channel
4. 客户端读空闲 (n个4s) + x未收到回复,重连
5. n取2为推荐,x取1
对于netty而言:
客户端:
@Override public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception { if(evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if(event.state() == IdleState.WRITER_IDLE) {
// 好久(30s)没给服务端传数据了,给个心跳^^ping sendHeartbeat(ctx); } else if (event.state() == IdleState.READ_IDLE) { ctx.close(); logger.warn("服务端好几次未回传pong"); } } }
R 61 W 30
服务端:
@Override public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception { Channel channel = ctx.channel(); if(evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if(event.state() == IdleState.READ_IDLE) { logger.debug("客户端按约定已经n次超时未传输数据过来"); channel.close(); } } }
R 61
https://stackoverflow.com/questions/10585355/sending-websocket-ping-pong-frame-from-browser
关于本文的实践位于:https://www.cnblogs.com/silyvin/articles/9796887.html