Netty 读写检测机制(心跳)

一、创建服务端

1、MyServer 类

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();
        }
    }
}

  增加日志处理器

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秒钟没有读事件

  7秒钟没有写事件

  10秒钟没有读写事件

3、处理器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().remoteAddress() + "超时事件: " + eventType);
            //关闭连接
            ctx.channel().close();
        }
    }
}

  

二、客户端代码同上一篇一致

三、测试

启动服务端和客户端

1、读空闲

可以发现,5秒钟没有读到消息,将触发超时事件: 读空闲

2、写空闲

客户端一直写

服务端没有写,7秒所有触发写空闲事件

3、读写空闲

把读写空闲事件时间改为3秒

重启服务端和客户端

猜你喜欢

转载自www.cnblogs.com/linlf03/p/11298431.html