~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
以下处理方法都是基于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一定要注意顺序