欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Netty心跳检测(1)

程序员文章站 2024-03-23 22:45:04
...

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();
					}
				}
				
				
			}
		
	}
		
	
	
	
}
相关标签: Netty

上一篇: Luogu P3489 [POI2009]WIE-Hexer

下一篇: