Netty心跳机制案例

    科技2022-07-13  108

    Netty心跳机制

    项目结构

    Server

    public class MyServer { public static void main(String[] args) throws InterruptedException { NioEventLoopGroup bossGroup = new NioEventLoopGroup(); NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup,workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO))//在bossGroup 增加日志处理器 .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //加入一个netty 提供的IdleStateHandler //IdleStateHandler 是netty 提供的处理空闲状态的处理器 //long readerIdleTime : 多长时间Server没读事件发生,就会发送一个心跳检测包,检测是否还是连接 //long writerIdleTime : 多长时间Server没写事件发生,就会发送一个心跳检测包,检测是否还是连接 //long allIdleTime : 多长时间Server没读写事件发生,就会发送一个心跳检测包,检测是否还是连接 //当IdleStateHandler触发后,会传递给管道的下一个handler处理,通过handler的userEventTiggered方法处理 pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS)); //加入对空闲检测进一步处理的handler(自定义) pipeline.addLast(new MyServerHandler()); } }); ChannelFuture channelFuture = serverBootstrap.bind(6666).sync(); channelFuture.channel().closeFuture().sync(); }finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }

    ServerHandler

    public class MyServerHandler extends ChannelInboundHandlerAdapter { /** * @param ctx 上下文 * @param evt 上一个handler 传过来的事件 * @throws Exception */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent){ //将evt转型IdleStateEvent IdleStateEvent event = (IdleStateEvent) evt; String evenType = null; switch (event.state()){ case READER_IDLE: evenType = "读空闲"; break; case WRITER_IDLE: evenType = "写空闲"; break; case ALL_IDLE: evenType = "读写空闲"; break; } System.out.println(ctx.channel().remoteAddress() + "--超时事件--"+evenType); } } }

    客户端这里就不写了直接使用上一个案例聊天室的客户端

    Processed: 0.015, SQL: 8