zoukankan      html  css  js  c++  java
  • 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秒

    重启服务端和客户端

  • 相关阅读:
    BZOJ1800 fly 飞行棋 [几何]
    Cf #434 Div.1 D Wizard's Tour [构造题]
    Last mile of the way [树形dp+重链剖分]
    World Of Our Own [Lucas+思维题]
    vue 初级小总结
    转-redux-saga
    【转】react-native开发混合App-github开源项目
    react中路由的跳转
    Lodash 浓缩
    jq的attr、prop和data区别
  • 原文地址:https://www.cnblogs.com/linlf03/p/11298431.html
Copyright © 2011-2022 走看看