Netty心跳检测(1)

来源:互联网 发布:淘宝狗粮店铺简介文案 编辑:程序博客网 时间:2024/05/16 17:27

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;@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("开始时间"+"---"+ new Date());System.out.println("ClientHandler.channelActive()");ctx.fireChannelActive();}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {System.out.println("ClientHandler.channelInactive()");}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {String mString = (String) msg;System.out.println(mString);}@Overridepublic 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;@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {super.channelActive(ctx);}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {super.channelInactive(ctx);}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {System.out.println("服务器读取"+"---"+new Date());System.out.println("Server:"+msg.toString()+"---"+new Date());}@Overridepublic 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();}}}}}