netty客户端同步连接NettyClinet

2019-10-17  本文已影响0人  next_discover
public class NettyClinet {


    private String host;
    private int port;

    private static Channel channel;

    public NettyClinet(){

    }

    public NettyClinet(String host, int port) {
        this.host = host;
        this.port = port;
    }



    public  void start()  {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .channel(NioSocketChannel.class)
                .handler(new ClientChannelInitializer(host,port));

            ChannelFuture f = b.connect(host,port).sync();

            //断线重连
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (!channelFuture.isSuccess()) {
                        final EventLoop loop = channelFuture.channel().eventLoop();
                        loop.schedule(new Runnable() {
                            @Override
                            public void run() {
                                log.error("服务端链接不上,开始重连操作...");
                                System.err.println("服务端链接不上,开始重连操作...");
                                start();
                            }
                        }, 1L, TimeUnit.SECONDS);
                    } else {
                        channel = channelFuture.channel();
                        log.info("服务端链接成功...");
                        System.err.println("服务端链接成功...");
                    }
                }
            });

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new NettyClinet ("127.0.0.1",8000).start();
    }
}

上一篇下一篇

猜你喜欢

热点阅读