Netty 超时机制及心跳程序实现

简介: 本文介绍了 Netty 超时机制的原理,以及如何在连接闲置时发送一个心跳来维持连接。 Netty 超时机制的介绍 Netty 的超时类型 IdleState 主要分为: ALL_IDLE : 一段时间内没有数据接收或者发送 READER_IDLE : 一段时间内没有数据接收 WRITER...

本文介绍了 Netty 超时机制的原理,以及如何在连接闲置时发送一个心跳来维持连接。

Netty 超时机制的介绍

Netty 的超时类型 IdleState 主要分为:

  • ALL_IDLE : 一段时间内没有数据接收或者发送
  • READER_IDLE : 一段时间内没有数据接收
  • WRITER_IDLE : 一段时间内没有数据发送

在 Netty 的 timeout 包下,主要类有:

  • IdleStateEvent : 超时的事件
  • IdleStateHandler : 超时状态处理
  • ReadTimeoutHandler : 读超时状态处理
  • WriteTimeoutHandler : 写超时状态处理

其中 IdleStateHandler 包含了读\写超时状态处理,比如

private static final int READ_IDEL_TIME_OUT = 4; // 读超时 private static final int WRITE_IDEL_TIME_OUT = 5;// 写超时 private static final int ALL_IDEL_TIME_OUT = 7; // 所有超时 new IdleStateHandler(READ_IDEL_TIME_OUT, WRITE_IDEL_TIME_OUT, ALL_IDEL_TIME_OUT, TimeUnit.SECONDS)); 

上述例子,在 IdleStateHandler 中定义了读超时的时间是 4 秒, 写超时的时间是 5 秒,其他所有的超时时间是 7 秒。

应用 IdleStateHandler

既然 IdleStateHandler 包括了读\写超时状态处理,那么很多时候 ReadTimeoutHandler 、 WriteTimeoutHandler 都可以不用使用。定义另一个名为 HeartbeatHandlerInitializer 的 ChannelInitializer :

public class HeartbeatHandlerInitializer extends ChannelInitializer<Channel> { private static final int READ_IDEL_TIME_OUT = 4; // 读超时 private static final int WRITE_IDEL_TIME_OUT = 5;// 写超时 private static final int ALL_IDEL_TIME_OUT = 7; // 所有超时 @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new IdleStateHandler(READ_IDEL_TIME_OUT, WRITE_IDEL_TIME_OUT, ALL_IDEL_TIME_OUT, TimeUnit.SECONDS)); // 1 pipeline.addLast(new HeartbeatServerHandler()); // 2 } } 
  1. 使用了 IdleStateHandler ,分别设置了读、写超时的时间
  2. 定义了一个 HeartbeatServerHandler 处理器,用来处理超时时,发送心跳

定义了一个心跳处理器

public class HeartbeatServerHandler extends ChannelInboundHandlerAdapter { // Return a unreleasable view on the given ByteBuf // which will just ignore release and retain calls. private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled .unreleasableBuffer(Unpooled.copiedBuffer("Heartbeat", CharsetUtil.UTF_8)); // 1 @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { // 2 IdleStateEvent event = (IdleStateEvent) evt; String type = ""; if (event.state() == IdleState.READER_IDLE) { type = "read idle"; } else if (event.state() == IdleState.WRITER_IDLE) { type = "write idle"; } else if (event.state() == IdleState.ALL_IDLE) { type = "all idle"; } ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate()).addListener( ChannelFutureListener.CLOSE_ON_FAILURE); // 3 System.out.println( ctx.channel().remoteAddress()+"超时类型:" + type); } else { super.userEventTriggered(ctx, evt); } } } 
  1. 定义了心跳时,要发送的内容
  2. 判断是否是 IdleStateEvent 事件,是则处理
  3. 将心跳内容发送给客户端

服务器

服务器代码比较简单,启动后侦听 8082 端口

public final class HeartbeatServer { static final int PORT = 8082; public static void main(String[] args) throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HeartbeatHandlerInitializer()); // Start the server. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } 

客户端测试

客户端用操作系统自带的 Telnet 程序即可:

telnet 127.0.0.1 8082

效果

转自http://waylau.com/netty-time-out-and-heartbeat/?utm_source=tuicool&utm_medium=referral

作者:Bonker
出处:http://www.cnblogs.com/Bonker
QQ:519841366
       
本页版权归作者和博客园所有,欢迎转载,但未经作者同意必须保留此段声明, 且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利
目录
相关文章
|
3月前
|
监控 网络协议 调度
Netty Review - 深入探讨Netty的心跳检测机制:原理、实战、IdleStateHandler源码分析
Netty Review - 深入探讨Netty的心跳检测机制:原理、实战、IdleStateHandler源码分析
110 0
|
4月前
|
网络协议 调度
Netty心跳检测
客户端的心跳检测对于任何长连接的应用来说,都是一个非常基础的功能。要理解心跳的重要性,首先需要从网络连接假死的现象说起。
|
8月前
|
Nacos
Netty自定义消息协议的实现逻辑处理粘包拆包、心跳机制
Netty自定义消息协议的实现逻辑处理粘包拆包、心跳机制
106 0
Netty(五)之心跳机制与重连
文章目标 1)实现客户端和服务端的心跳 2)心跳多少次没有应答断开处理 3)客户端宕机通知服务端 4)服务端宕机客户端重连
119 0
Netty(五)之心跳机制与重连
|
JSON 前端开发 安全
Netty进阶 -- 非阻塞网络编程 实现群聊+私聊+心跳检测系统
Netty进阶 -- 非阻塞网络编程 实现群聊+私聊+心跳检测系统
146 0
Netty进阶 -- 非阻塞网络编程 实现群聊+私聊+心跳检测系统
|
监控 数据可视化 Java
Netty(一) SpringBoot 整合长连接心跳机制(下)
Netty 是一个高性能的 NIO 网络框架,本文基于 SpringBoot 以常见的心跳机制来认识 Netty。
Netty(一) SpringBoot 整合长连接心跳机制(中)
Netty 是一个高性能的 NIO 网络框架,本文基于 SpringBoot 以常见的心跳机制来认识 Netty。
|
监控 Java
Netty(一) SpringBoot 整合长连接心跳机制(上)
Netty 是一个高性能的 NIO 网络框架,本文基于 SpringBoot 以常见的心跳机制来认识 Netty。
|
JSON 安全 JavaScript
Netty进阶 -- 非阻塞网络编程 实现群聊+私聊+心跳检测系统
通俗易懂带你完成Netty进阶 -- 非阻塞网络编程 实现群聊+私聊+心跳检测系统
197 1
Netty进阶 -- 非阻塞网络编程 实现群聊+私聊+心跳检测系统