IdleStateHandler
Netty中的心跳检测机制,根据这个处理器能及时的检测到读/写/读写空闲状态,根据状态进行相应的处理。
1
2
3
4 1Triggers an {@link IdleStateEvent} when a {@link Channel} has not performed
2read, write, or both operation for a while.
3
4
当没有执行读、写、读写时触发IdleStateEvent。
触发IdleStateEvent后,会将Event传递给pipeline的下一个Handler的userEventTriggered方法,重写此方法对空闲事件进行处理。
代码示例
Server:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 1 NioEventLoopGroup bossGroup = new NioEventLoopGroup();
2 NioEventLoopGroup workGroup = new NioEventLoopGroup();
3 try{
4
5 ServerBootstrap serverBootstrap = new ServerBootstrap();
6 serverBootstrap.group(bossGroup,workGroup).channel(NioServerSocketChannel.class)
7 .handler(new LoggingHandler(LogLevel.INFO))
8 .childHandler(new ChannelInitializer<SocketChannel>() {
9 @Override
10 protected void initChannel(SocketChannel ch) throws Exception {
11 ChannelPipeline pipeline = ch.pipeline();
12 /**
13 * 1.long readerIdleTime 超过这个时间没有读,就会发送心跳包进行检测
14 * 2.long writerIdleTime 超过这个时间没有读,就会发送心跳包进行检测
15 * 3.long allIdleTime 读超过这个时间没有读写,就会发送心跳包进行检测
16 *
17 * 如果没有进行读、写、读写,就会触发IdleStateEvent事件
18 * 当触发了IdleStateEvent触发后,就会传递给pipeline的下一个handler的userEventTriggered去处理
19 */
20 pipeline.addLast(new IdleStateHandler(3,5,7,TimeUnit.SECONDS));
21 pipeline.addLast(new HeartBeatServerHandler());
22 }
23 });
24 ChannelFuture channelFuture = serverBootstrap.bind(8090).sync();
25 channelFuture.channel().closeFuture().sync();
26
27 }finally {
28 bossGroup.shutdownGracefully();
29 workGroup.shutdownGracefully();
30 }
31
32
ServerHandler:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 1public class ServerHandler extends ChannelInboundHandlerAdapter {
2
3 @Override
4 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
5 if (evt instanceof IdleStateEvent){
6 IdleStateEvent event = (IdleStateEvent) evt;
7 switch (event.state()){
8 case READER_IDLE:
9 System.out.println("read空闲");
10 break;
11 case WRITER_IDLE:
12 System.out.println("write空闲");
13 break;
14 case ALL_IDLE:
15 System.out.println("readwrite空闲");
16 break;
17 }
18 // 根据读写空闲进行相应的的操作
19 ctx.close();
20 }
21 }
22
23
24}
25
26
27