从零学Netty(十)Netty心跳处理器

it2024-10-21  37

简介

首先要说一下  IdleStateHandler  是 netty 提供的处理空闲状态的处理器

参数说明:

long readerIdleTime : 表示多长时间没有读, 就会发送一个心跳检测包检测是否连接long writerIdleTime : 表示多长时间没有写, 就会发送一个心跳检测包检测是否连接long allIdleTime : 表示多长时间没有读写, 就会发送一个心跳检测包检测是否连接

当 IdleStateEvent 触发后 , 就会传递给管道 的下一个handler去处理

通过调用(触发)下一个handler 的 userEventTiggered , 在该方法中去处理 IdleStateEvent(读空闲,写空闲,读写空闲)

实例demo

服务端实现

/** * 服务端 * * @author LionLi */ public class MyServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) // 主业务处理 .channel(NioServerSocketChannel.class) // 日志处理器 .handler(new LoggingHandler(LogLevel.INFO)) // 子业务处理 .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); // 加入一个netty 提供 IdleStateHandler pipeline.addLast(new IdleStateHandler(3, 5, 10, TimeUnit.SECONDS)); // 加入一个对空闲检测进一步处理的handler(自定义) pipeline.addLast(new MyServerHandler()); } }); ChannelFuture channelFuture = serverBootstrap.bind(8088).sync(); channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }

服务端业务处理实现

/** * 心跳业务处理 * * @author LionLi */ public class MyServerHandler extends ChannelInboundHandlerAdapter { /** * 事件触发 */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { 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; } System.out.println(ctx.channel().remoteAddress() + "--超时时间--" + eventType); System.out.println("服务器做相应处理.."); // 这里可以执行一些业务 // 比如: 如果发生空闲,我们关闭通道 // ctx.channel().close(); } } }

客户端实现(用于测试)

/** * 测试客户端 * * @author LionLi */ public class TestClient { public static void main(String[] args) { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new SimpleChannelInboundHandler<String>(){ @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println(msg.trim()); } }); } }); ChannelFuture channelFuture = bootstrap.connect("localhost", 8088).sync(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } }

测试

分别启动服务端与客户端  等待数秒观察服务端日志

针对不同的状态对应编写不同的业务处理即可

 

项目已上传到gitee

地址: netty-demo

如果帮到您了,请帮忙点个star

最新回复(0)