Class IdleStateHandler

java.lang.Object
org.jboss.netty.channel.SimpleChannelUpstreamHandler
org.jboss.netty.handler.timeout.IdleStateHandler
All Implemented Interfaces:
ChannelHandler, ChannelUpstreamHandler, LifeCycleAwareChannelHandler, ExternalResourceReleasable

Triggers an IdleStateEvent when a Channel has not performed read, write, or both operation for a while.

Supported idle states

PropertyMeaning
readerIdleTime an IdleStateEvent whose state is IdleState.READER_IDLE will be triggered when no read was performed for the specified period of time. Specify 0 to disable.
writerIdleTime an IdleStateEvent whose state is IdleState.WRITER_IDLE will be triggered when no write was performed for the specified period of time. Specify 0 to disable.
allIdleTime an IdleStateEvent whose state is IdleState.ALL_IDLE will be triggered when neither read nor write was performed for the specified period of time. Specify 0 to disable.
 // 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));
 ...
 
The Timer which was specified when the IdleStateHandler is created should be stopped manually by calling releaseExternalResources() or Timer.stop() when your application shuts down.
See Also: