为什么需要心跳包???
心跳包主要是用来做TCP长连接保活的。有时 socket 虽然是连接的但中间网络可能有问题,这时你还在不停的往外发送数据,但对方是收不到的,你不知道对方是不是还活着,不知道 socket 通道是不是还是联通的。 心跳包就是你发送一些试探包给对方,对方回应,如果一定时间内比如30秒内没有收到任何数据,说明对方或网络可能有问题了。这时你主动断开 socket 连接,避免浪费资源。
TCP 本来就有 keepAlive 机制为什么还需要应用层自己实现心跳???
TCP keepAlive 也是在一定时间内(默认2小时)socket 上没有接收到数据时主动断开连接,避免浪费资源,这时远端很可能已经down机了或中间网络有问题。也是通过发送一系列试探包看有没有回应来实现的。
但 TCP keepAlive 检测的主要是传输层的连通性,应用层心跳主要检测应用层服务是否可用,如如果出现死锁虽然 socket 是联通的但服务已经不可用。
TCP keepAlive 依赖操作系统,默认是关闭的,需要修改操作系统配置打开。
netty 中通过 IdleStateHandler 在空闲的时候发送心跳包
为什么在空闲的时候发送心跳包,而不是每隔固定时间发送???
这个是显而易见的,正常通信时说明两端连接是没有问题的,所以只在空闲的时候发送心跳包。如果每隔固定时间发送就会浪费资源占用正常通信的资源。
假设现在要做一个手机端推送的项目,所有手机通过 TCP 长连接连接到后台服务器。心跳机制是这样的:
- 手机端在写空闲的时候发送心跳包给服务端,用 IdleStateHandler 来做 socket 的空闲检测。 如果 5 秒内没有写任何数据,则发送心跳包到服务端
ch.pipeline().addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS));
ch.pipeline().addLast(new HeartbeatKeeper());
@ChannelHandler.Sharable
public class HeartbeatKeeper extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleState state = ((IdleStateEvent) evt).state();
if (state == IdleState.WRITER_IDLE) {
System.out.println("client send heart beat");
ctx.channel().writeAndFlush("heart beat\n");
}
} else {
super.userEventTriggered(ctx, evt);
}
}
}
- 服务端设置读超时,如果 30 秒内没有收到一个客户端的任何数据则关闭连接。
ch.pipeline().addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS)); ch.pipeline().addLast(new IdleStateTrigger()); @ChannelHandler.Sharable public class IdleStateTrigger extends ChannelInboundHandlerAdapter { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleState state = ((IdleStateEvent) evt).state(); if (state == IdleState.READER_IDLE) { ctx.channel().close(); } } else { super.userEventTriggered(ctx, evt); } } }
服务端接收到心跳包后要不要回复???
看其他博客说不要回复,如果有 10万空闲连接,光回复心跳包就要占用大量资源。服务端读超时后直接关闭连接,客户端再进行重连。
断线重连
断线重连也很简单就是在 channelInactive 的时候重新 connect 就行了。参考其他博客专门用一个 ChannelInboundHandler 来处理断线重连。
@ChannelHandler.Sharable public class ConnectionWatchDog extends ChannelInboundHandlerAdapter implements TimerTask { private final Bootstrap bootstrap; private final String host; private final int port; private volatile boolean reconnect; private int attempts; private Channel channel; private HashedWheelTimer timer = new HashedWheelTimer(); private int reconnectDelay = 5; public ConnectionWatchDog(Bootstrap bootstrap, String host, int port, boolean reconnect) { this.bootstrap = bootstrap; this.host = host; this.port = port; this.reconnect = reconnect; } public Channel getChannel() { return this.channel; } public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("channelActive"); channel = ctx.channel(); ctx.fireChannelActive(); } public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("channelInactive"); ctx.fireChannelInactive(); channel = null; if (reconnect) { attempts = 0; scheduleReconnect(); } } private void connect() { bootstrap.connect(host, port).addListener((future) -> { if (future.isSuccess()) { System.out.println("connected to " + host + ":" + port); attempts = 0; } else { System.out.println("connect failed " + attempts + " , to reconnect after " + reconnectDelay + " 秒"); // 这里现在每5秒重连一次直到连接上,可自己实现重连逻辑 scheduleReconnect(); } }); } public void run(Timeout timeout) { synchronized (this.bootstrap) { ++attempts; connect(); } } private void scheduleReconnect() { timer.newTimeout(this, reconnectDelay, TimeUnit.SECONDS); } public void setReconnect(boolean reconnect) { this.reconnect = reconnect; } }
这个 watchDog Handler 应当放在 ChannelPipeline 的最前面
public void connect(String host, int port) { Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup()) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000); watchDog = new ConnectionWatchDog(bootstrap, host, port, true); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(watchDog); ch.pipeline().addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS)); ch.pipeline().addLast(new HeartbeatKeeper()); ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8)); ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8)); ch.pipeline().addLast(new ClientDemoHandler()); } }); // 这里如果第一次连接不成功也可以尝试多次连接 bootstrap.connect(host, port); }
DEMO:
https://github.com/lesliebeijing/Netty-Demo基于 Netty 写的一个简单的推送 DEMO,可用在手机端推送
https://github.com/lesliebeijing/EncPushNetty 客户端用在 Android 中也很稳定,我们的物联网项目Android和后台都是用的 Netty。