Netty心跳检测(1)

本文通过实战演示了如何使用Netty实现客户端与服务器之间的心跳检测机制。客户端会在连接建立后发送消息,并通过IdleStateHandler监测连接空闲状态。服务器端则会监听客户端的活动,若长时间未收到消息将断开连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Netty心跳检测(1)

public class HClient {

	public void connect(String host,int port) throws InterruptedException {
		 EventLoopGroup group = new NioEventLoopGroup();
		 Bootstrap bootstrap = new Bootstrap();
		 bootstrap.group(group).channel(NioSocketChannel.class)
         .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ChannelPipeline p = ch.pipeline();
                 p.addLast("decoder", new StringDecoder());
                 p.addLast("encoder", new StringEncoder());
                 p.addLast("ping", new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));
                 p.addLast(new ClientHandler());
             }
         });

		ChannelFuture future = bootstrap.connect(host,port).sync();
		future.channel().writeAndFlush("hello,I am from client");
		
		
	}
	
	public static void main(String[] args) throws InterruptedException {
				HClient client  = new HClient();
				client.connect("127.0.0.1",4473);
	}

}
public class HServer {

	public void start(int port) throws InterruptedException {
		 EventLoopGroup bossGroup = new NioEventLoopGroup(1);
	     EventLoopGroup workerGroup = new NioEventLoopGroup();
	     ServerBootstrap serverBootstrap = new ServerBootstrap();
	     serverBootstrap.group(bossGroup,workerGroup)
	     .channel(NioServerSocketChannel.class)
	     .localAddress(new InetSocketAddress(port))
	     .childHandler(new ChannelInitializer<SocketChannel>() {
             
             private static final int READ_IDEL_TIME_OUT = 6; // 读超时
             private static final int WRITE_IDEL_TIME_OUT = 0;// 写超时
             private static final int ALL_IDEL_TIME_OUT = 0; // 所有超时
             
             protected void initChannel(SocketChannel ch) throws Exception {
                 ch.pipeline().addLast(new IdleStateHandler(READ_IDEL_TIME_OUT,
                         WRITE_IDEL_TIME_OUT, ALL_IDEL_TIME_OUT, TimeUnit.SECONDS));
                 ch.pipeline().addLast("decoder", new StringDecoder());
                 ch.pipeline().addLast("encoder", new StringEncoder());
                 ch.pipeline().addLast(new ServerHandler());
             };
             
         }).option(ChannelOption.SO_BACKLOG, 128)   
         .childOption(ChannelOption.SO_KEEPALIVE, true);
	     ChannelFuture future = serverBootstrap.bind(port).sync();
	     System.out.println("Server start listen at " + port );
	     future.channel().closeFuture().sync();
	}
	
	public static void main(String[] args) throws InterruptedException {
			HServer server = new HServer();
			server.start(4473);
	}

}
public class ClientHandler extends ChannelInboundHandlerAdapter{
	static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Heartbeat",
            CharsetUtil.UTF_8));
	
	int TRY_TIMES = 3;
	int current_time = 0;
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
				System.out.println("开始时间"+"---"+ new Date());
				System.out.println("ClientHandler.channelActive()");
				ctx.fireChannelActive();
				
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
				System.out.println("ClientHandler.channelInactive()");
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
				String mString = (String) msg;
				System.out.println(mString);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
			System.out.println("触发时间"+"---"+new Date());
			if (evt instanceof IdleStateEvent) {
				IdleStateEvent event = (IdleStateEvent) evt;
				if (event.state() == IdleState.WRITER_IDLE) {
						if (current_time<=TRY_TIMES) {
							ctx.channel().writeAndFlush(HEARTBEAT_SEQUENCE.duplicate());
							current_time++;
						}
				}
				
				
			}
			
	}

	
	
}
public class ServerHandler extends ChannelInboundHandlerAdapter{
	int loss_connect_time = 0;
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
				System.out.println("服务器读取"+"---"+new Date());
				System.out.println("Server:"+msg.toString()+"---"+new Date());
				
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
			if (evt instanceof IdleStateEvent) {
				IdleStateEvent event = (IdleStateEvent) evt;
				if (event.state() == IdleState.READER_IDLE) {
					loss_connect_time++;
					System.out.println("长时间没接收到客户端信息");
					if (loss_connect_time>=2) {
						ctx.channel().close();
					}
				}
				
				
			}
		
	}
		
	
	
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值