Netty入門(九)空閑連接以及超時


  檢測空閑連接和超時是為了及時釋放資源。常見的方法是發送消息來測試一個不活躍的連接,通常稱為“心跳”。

  Netty 提供了幾個 ChannelHandler 來實現此目的,如下:

  

  下面是 IdleStateHandler 的一個簡單使用:

 1 /**
 2  * 空閑連接
 3  * 當超過60s沒有數據收到時,就發送心跳到遠端
 4  * 如果沒有回應,關閉連接
 5  */
 6 public class IdleStateHandlerInitializer extends ChannelInitializer<Channel> {
 7 
 8     @Override
 9     protected void initChannel(Channel ch) throws Exception {
10         ChannelPipeline pipeline = ch.pipeline();
11         // 若60s沒有收到消息,調用userEventTriggered方法
12         pipeline.addLast(new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
13         pipeline.addLast(new HeartBeatHandle());
14     }
15     
16     public static final class HeartBeatHandle extends ChannelInboundHandlerAdapter {
17         private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(
18                 Unpooled.copiedBuffer("HEARTBEAT", CharsetUtil.UTF_8));
19         
20         @Override
21         public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
22             if(evt instanceof IdleStateEvent) {
23                 // 發送心跳到遠端
24                 ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate())
25                     .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);    // 關閉連接
26             } else {
27                 // 傳遞給下一個處理程序
28                 super.userEventTriggered(ctx, evt);
29             }
30         }
31     }
32 
33 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM