美文网首页
netty客户端同步连接NettyClinet

netty客户端同步连接NettyClinet

作者: next_discover | 来源:发表于2019-10-17 20:08 被阅读0次
    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();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:netty客户端同步连接NettyClinet

          本文链接:https://www.haomeiwen.com/subject/ngovmctx.html