Netty 客户端重连

客户端代码

public class NettyClient {

    static  NioEventLoopGroup group = new NioEventLoopGroup(8);
    static  Bootstrap bootstrap = new Bootstrap();
    static volatile Channel channel = null;
    public static void main(String[] args) throws InterruptedException {
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast("ping", new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS))
                                .addLast(new ObjectEncoder())
                                .addLast(new ObjectDecoder((s)->{
                                    return String.class;
                                })).addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                System.out.println("断线了");
                                ctx.channel().eventLoop().schedule(()->{
                                    System.out.println("断线重连");
                                    connect();
//                                    ctx.connect(new InetSocketAddress("127.0.0.1", 8666));
//                                    ctx.channel().close();
                                }, 1L, TimeUnit.SECONDS);
                                super.channelInactive(ctx);
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                cause.printStackTrace();
                                ctx.close();
                            }

                            @Override
                            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                if (evt instanceof IdleStateEvent){
//                                    if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE){
//                                        System.out.println("度空闲");
//                                        ctx.writeAndFlush("sasa");
//                                    }
                                }else{
                                    super.userEventTriggered(ctx, evt);
                                }
                            }

                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                System.out.println("连接 == " + ctx);
                                channel = ctx.channel();
                                super.channelActive(ctx);
                            }
                        });
                    }
                });
        connect();

        Thread thread = new Thread(){
            @Override
            public void run() {
                int num = 100;
                while (num -- > 0){
//                    try {
//                        Thread.sleep(1000L);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }

                    try {
                        if (channel != null && channel.isActive()){
                            channel.writeAndFlush("测试" + UUID.randomUUID().toString() + "#@");
                        }else if(channel == null || !channel.isActive()){
                            System.out.println("不可写 稍等 ++++");
                            Thread.sleep(1000L);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.setDaemon(true);
        thread.start();
    }

    private static void connect(){
        ChannelFuture future = bootstrap.connect("127.0.0.1", 8666)
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture ch) throws Exception {
                        if (!ch.isSuccess()) {
                            ch.channel().close();
                            final EventLoop loop = ch.channel().eventLoop();
                            loop.schedule(new Runnable() {
                                @Override
                                public void run() {
                                    System.err.println("服务端链接不上,开始重连操作...");
                                    connect();
//                                    ch.(new InetSocketAddress("127.0.0.1", 8666));
//                                    ch.channel().close();
                                }
                            }, 1L, TimeUnit.SECONDS);
                        } else {
                            ch.channel().writeAndFlush("你好");
                            System.err.println("服务端链接成功...");
                        }
                    }
                });
    }

}

服务端代码:

public class NettyServer {

    public static final int port = 8666;

    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup(8);
        NioEventLoopGroup work = new NioEventLoopGroup(16);
        try {


            ServerBootstrap server = new ServerBootstrap().group(boss, work);
            server.channel(NioServerSocketChannel.class)
                    .handler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(ServerSocketChannel ch) throws Exception {
                            System.out.println("服务启动中");
                        }
                    })
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.SO_REUSEADDR, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new IdleStateHandler(true, 5, 3, 0, TimeUnit.SECONDS))
                                    .addLast(new ObjectEncoder())
                                    .addLast(new ObjectDecoder((s)->{
                                        return String.class;
                                    }))
                                    .addLast(new ChannelInboundHandlerAdapter() {
                                        @Override
                                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                            try {
                                                System.out.println(msg);
                                            }finally {
                                                ReferenceCountUtil.release(msg);
                                            }
                                        }

                                        @Override
                                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

                                            if (evt instanceof IdleStateEvent) {
                                                System.out.println(((IdleStateEvent) evt).state() + ">>>" + ctx.channel());
                                            }
                                            super.userEventTriggered(ctx, evt);
                                        }
                                    });
                        }

                        @Override
                        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                            System.out.println("有新连接了 ++++ ");
                            super.handlerAdded(ctx);
                        }

                    });

            ChannelFuture future = server.bind(port).sync();
            future.channel().closeFuture().sync();
            future.addListener(new GenericFutureListener>() {
                @Override
                public void operationComplete(Future future) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("服务启动成功");
                    } else {
                        System.out.println("服务启动失败");
                    }
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }

}

你可能感兴趣的:(Netty,笔记)