First, create a server
1, MyServer class
public class MyServer { public static void main(String[] args) throws Exception{ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try{ ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) //增加日志处理器 .childHandler(new MyServerInitializer()); ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); channelFuture.channel().closeFuture().sync(); }finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
Increase the log processor
2、MyServerInitializer
public class MyServerInitializer extends ChannelInitializer<SocketChannel>{ protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast(new IdleStateHandler(5, 7, 10, TimeUnit.SECONDS)); pipeline.addLast(new MyServerHandle()); } }
5 seconds did not read event
7 seconds did not write events
10 seconds to read and write no event
3, the processor MyServerHandle
public class MyServerHandle extends ChannelInboundHandlerAdapter { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if(evt instanceof IdleStateEvent){ IdleStateEvent event = (IdleStateEvent)evt; String eventType = null; switch (event.state()){ case READER_IDLE: eventType = "读空闲"; break; case WRITER_IDLE: eventType = "写空闲"; break; case ALL_IDLE: eventType = "读写空闲"; break; } CommonUtil.println (ctx.channel () of the remoteAddress () + "timeout event:." The eventType +); // close the connection . Ctx.channel () Close (); } } }
Second, the client code above a consistent
Third, the test
Start the server and client
1, read idle
Can be found, not read the message 5 seconds, it will trigger a timeout event: free read
2, write idle
The client has been written
The server did not write, write seven seconds idle all trigger events
3, free to read and write
The reader idle event time changed three seconds
Restart the server and the client