Netty连接超时处理方法

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

以下处理方法都是基于netty3.5.13版本。

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


官方给出的处理方法:

// An example that sends a ping message when there is no outbound traffic
 // for 30 seconds.  The connection is closed when there is no inbound traffic
 // for 60 seconds.

 public class MyPipelineFactory implements ChannelPipelineFactory {

     private final Timer timer;
     private final ChannelHandler idleStateHandler;

     public MyPipelineFactory(Timer timer) {
         this.timer = timer;
         this.idleStateHandler = new IdleStateHandler(timer, 60, 30, 0), // timer must be shared.
     }

     public ChannelPipeline getPipeline() {
         return Channels.pipeline(
             idleStateHandler,
             new MyHandler());
     }
 }

 // Handler should handle the IdleStateEvent triggered by IdleStateHandler.
 public class MyHandler extends IdleStateAwareChannelHandler {

     @Override
     public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) {
         if (e.getState() == IdleState.READER_IDLE) {
             e.getChannel().close();
         } else if (e.getState() == IdleState.WRITER_IDLE) {
             e.getChannel().write(new PingMessage());
         }
     }
 }

 ServerBootstrap bootstrap = ...;
 Timer timer = new HashedWheelTimer();
 ...
 bootstrap.setPipelineFactory(new MyPipelineFactory(timer));


需要注意的两点:

1、IdleStateHandler构造函数参数含义


   构造函数体

   public IdleStateHandler(Timer timer,
                        int readerIdleTimeSeconds,
                        int writerIdleTimeSeconds,
                        int allIdleTimeSeconds)

      这里的timer是org.jboss.netty.util.Timer,而不是java.util.Timer

   readerIdleTimeSeconds、固定时间(单位为秒)检测一下是否有接收到消息。指定0时,禁用

      writerIdleTimeSeconds、固定时间(单位为秒)写一次消息。指定0时,禁用

allIdleTimeSeconds、无论是读还是写都在指定时间内进行。指定0时,禁用

2、pipeline在执行事件回调的时候,是后进先出规则的,所有在加载idleStathandler和MyHandler一定要注意顺序





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值