Netty.心跳

1、Netty的心跳,不像Mina,Mina有个心跳基类,而Netty没有,Netty的心跳也是继承ChannelInboundHandlerAdapter重写channelRead;

以下代码实现:服务端30读空闲,则给客户端发送‘+’,客户端收到后,回'-',如果服务端连续发送3次还是未收到‘-’,则断开连接


TcpServerInitializer 中主要看:

.addLast("ping", new IdleStateHandler(NettyConstants.READERIDLE_TIMESECONDS, 0, 0, TimeUnit.SECONDS))
.addLast("heartbeatHandler", new HeartbeatHandler_Read())


package com.sintech.initializer;

import java.util.concurrent.TimeUnit;

import com.sintech.handler.TcpInHandler;
import com.sintech.handler.TcpOutHandler;
import com.sintech.handler.keepalive.HeartbeatHandler_Read;
import com.sintech.message.codec.MessageDecoder;
import com.sintech.message.codec.MessageEncoder;
import com.sintech.utils.NettyConstants;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

public class TcpServerInitializer extends ChannelInitializer<SocketChannel> {
	
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ch.pipeline()
		//.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(this.getClass().getClassLoader()))) 
		.addLast(new LoggingHandler(LogLevel.DEBUG))
		// 30秒idle,如果连续3次idle,则断开连接
		.addLast("ping", new IdleStateHandler(NettyConstants.READERIDLE_TIMESECONDS, 0, 0, TimeUnit.SECONDS))
		.addLast("heartbeatHandler", new HeartbeatHandler_Read())
		// .addLast(new StringEncoder(CharsetUtil.UTF_8))
		// .addLast(new StringDecoder(CharsetUtil.UTF_8))
		.addLast(new MessageDecoder())
		.addLast(new MessageEncoder())
		.addLast("inHandler", new TcpInHandler())
		.addLast("outHandler", new TcpOutHandler())
		;
	}

}



package com.sintech.handler.keepalive;

import com.sintech.utils.NettyConstants;
import com.sintech.utils.NettyLogger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;


@Sharable
public class HeartbeatHandler_Read extends ChannelInboundHandlerAdapter {
	
	// 心跳失败计数器:未收到client端发送的ping请求
    private int unRecPingTimes = 0 ;
    
    // 定义服务端没有收到心跳消息的最大次数
    private static final int MAX_UN_REC_PING_TIMES = 3;
    
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		unRecPingTimes = 0;
		if(msg instanceof ByteBuf) {
			ByteBuf bb = (ByteBuf)msg;
			if(bb.readableBytes() == 1 && bb.getByte(0) == NettyConstants.PING) {
				ByteBuf b = ctx.alloc().buffer(1);
				// b.writeBytes(NettyConstants.PONG);
				b.writeByte(NettyConstants.PONG);
				ctx.writeAndFlush(b);
				bb.release();
			} else {
				super.channelRead(ctx, msg);
			}
		} else if (msg instanceof DatagramPacket) {
			DatagramPacket dp = (DatagramPacket) msg;
			
			ByteBuf bb = (ByteBuf) dp.copy().content();
            if(bb.readableBytes() == 1 && bb.getByte(0) == NettyConstants.PING) {
				ByteBuf b = ctx.alloc().buffer(1);
				// b.writeBytes(PONG);
				b.writeByte(NettyConstants.PONG);
				DatagramPacket dp2 = new DatagramPacket(b, dp.sender());
				ctx.writeAndFlush(dp2);
				dp.release();
			} else {
				super.channelRead(ctx, msg);
			}
		} else {
			super.channelRead(ctx, msg);
		}
		
	}
	
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		if (evt instanceof IdleStateEvent) {  
            IdleState state = ((IdleStateEvent) evt).state();  
            if (state == IdleState.READER_IDLE) {
            	unRecPingTimes++;
            	NettyLogger.getInstance().logInfo("第" + unRecPingTimes + "次IDLE", null);
            	if(unRecPingTimes >= MAX_UN_REC_PING_TIMES) {
            		ctx.close();
            	}
                
            }  
        } else {  
            super.userEventTriggered(ctx, evt);  
        }  
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值