netty processor can support idle detection for detecting mentality, when the server exceeded the wait time, not when an event occurs, the handler method will trigger userEventTriggered.
initializer
1 import io.netty.channel.ChannelInitializer; 2 import io.netty.channel.ChannelPipeline; 3 import io.netty.channel.socket.SocketChannel; 4 import io.netty.handler.timeout.IdleStateHandler; 5 6 import java.util.concurrent.TimeUnit; 7 8 public class MyServerInitlalizer extends ChannelInitializer<SocketChannel> { 9 @Override 10 protected void initChannel(SocketChannel ch) throws Exception { 11 Pipeline = the ChannelPipeline ch.pipeline (); 12 is 13 is // idle event processor read write Idle Idle 5s 3s idle write 7S 14 pipeline.addLast ( new new IdleStateHandler (5,7,3, TimeUnit.SECONDS)); // Idle not detected in a certain time interval reader 15 pipeline.addLast ( new new MyServerHandler ()); // custom event idle processor 16 . 17 } 18 }
handler
1 import io.netty.channel.ChannelHandlerContext; 2 import io.netty.channel.ChannelInboundHandler; 3 import io.netty.channel.ChannelInboundHandlerAdapter; 4 import io.netty.channel.SimpleChannelInboundHandler; 5 import io.netty.handler.timeout.IdleStateEvent; 6 7 public class MyServerHandler extends ChannelInboundHandlerAdapter { 8 @Override 9 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 10 //super.userEventTriggered (CTX, EVT); . 11 IF (EVT the instanceof IdleStateEvent) { // if it is an idle state 12 is IdleStateEvent Event = (IdleStateEvent) EVT; 13 is 14 String the eventType = null ; 15 16 Switch (event.state ()) { . 17 Case READER_IDLE: 18 is the eventType = "read idle" ; . 19 BREAK ; 20 is Case WRITER_IDLE: 21 is the eventType = "idle write" ; 22 is BREAK ; 23 is Case ALL_IDLE: 24 the eventType = "Idle reader" ; 25 BREAK ; 26 is } 27 28 System.out.println (ctx.channel () of the remoteAddress () + "timeout event:." + The eventType); 29 30 ctx.channel () .close (); 31 is } 32 } 33 is }