protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key)
      throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap
        .group(workerGroup)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
        .option(
            ChannelOption.TCP_NODELAY,
            Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true")))
        .option(
            ChannelOption.SO_REUSEADDR,
            Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true")));
    if (connectTimeout < 1000) {
      bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    } else {
      bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    }
    final NettyClientHandler handler = new NettyClientHandler(this, key);
    bootstrap.handler(
        new ChannelInitializer<SocketChannel>() {

          protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("decoder", new NettyProtocolDecoder());
            pipeline.addLast("encoder", new NettyProtocolEncoder());
            pipeline.addLast("handler", handler);
          }
        });
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(targetIP, targetPort)).sync();
    future.awaitUninterruptibly(connectTimeout);
    if (!future.isDone()) {
      LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
      throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    }
    if (future.isCancelled()) {
      LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
      throw new Exception(
          "Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    }
    if (!future.isSuccess()) {
      LOGGER.error(
          "Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
      throw new Exception(
          "Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
    }
    NettyClient client = new NettyClient(future, key, connectTimeout);
    handler.setClient(client);
    return client;
  }
  /**
   * create connection to remote server
   *
   * @return
   */
  public Channel connect() {
    // Start the connection attempt.
    //	while(true){
    if (channel == null) {
      try {
        // if(flag==1)
        // {
        handler = new MonitorHandler();
        MonitorInitializer mi = new MonitorInitializer(handler, false);

        Bootstrap b = new Bootstrap();
        // @TODO newFixedThreadPool(2);
        b.group(group).channel(NioSocketChannel.class).handler(mi);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        // Make the connection attempt.
        logger.info(host + ";" + port + "IN JobBid monitor");
        channel = b.connect(host, port).syncUninterruptibly();
        channel.awaitUninterruptibly(5000l);
        channel.channel().closeFuture().addListener(new MonitorClosedListener(this));
        // flag=0;
        // Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        if (N == Integer.MAX_VALUE) N = 1;
        else N++;
        // }
        // add listeners waiting to be added
        if (listeners.size() > 0) {
          for (MonitorListener ml : listeners) handler.addListener(ml);
          listeners.clear();
        }
      } catch (Exception ex) {
        logger.debug("failed to initialize the heartbeat connection");
        // logger.error("failed to initialize the heartbeat connection",
        // ex);
      }
    }

    if (channel != null && channel.isDone() && channel.isSuccess()) {

      logger.info("Channel is Created" + channel);
      return channel.channel();
    } else {
      logger.info("In Error from Establish Connection");
      throw new RuntimeException("Not able to establish connection to server");
    }
  }
示例#3
0
  public void run(URI uri) throws Exception {
    int port = uri.getPort() > 0 ? uri.getPort() : BaseTestConfig.HTTPS_PORT;
    String host = uri.getHost();

    // Configure SSL context if necessary.
    final SslContext sslCtx;
    sslCtx =
        SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    httpsInitializer = generateHttpsInitializer(sslCtx);
    try {
      Bootstrap b = new Bootstrap();
      b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
      b.group(group).channel(NioSocketChannel.class).handler(httpsInitializer);

      // Make the connection attempt.
      startTime = System.nanoTime();
      Channel ch = b.connect(host, port).sync().channel();
      localAddress = ch.localAddress();
      remoteAddress = ch.remoteAddress();

      sendRequests(uri.toURL(), ch);

      // Wait for the server to close the connection.
      ch.closeFuture().sync();
      endTime = System.nanoTime();
      long duration = endTime - startTime;
      logger.info(String.format("connection duration: %,dns (%d)", duration, duration));
    } finally {
      // Shut down executor threads to exit.
      group.shutdownGracefully();
    }
  }
示例#4
0
  public static void main(String[] args) throws InterruptedException {
    String host = "localhost";
    int port = 8080;

    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      Bootstrap b = new Bootstrap();
      b.group(workerGroup);
      b.channel(NioSocketChannel.class);
      b.option(ChannelOption.SO_KEEPALIVE, true);
      b.handler(
          new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
              ch.pipeline().addLast(new TimeDecoder(), new TimeClientHandler());
            }
          });

      ChannelFuture f = b.connect(host, port).sync();
      f.channel().closeFuture().sync();
    } finally {
      workerGroup.shutdownGracefully();
    }
  }
示例#5
0
  public void init(ChannelPipelineFactory factory) throws Exception {
    id =
        String.format("%1$020d", Math.abs(new Random(System.currentTimeMillis()).nextLong()))
            .getBytes();

    group = new OioEventLoopGroup();
    connectionlessBootstrap = new Bootstrap();
    connectionlessBootstrap.group(group);
    connectionlessBootstrap.option(ChannelOption.SO_BROADCAST, true);
    connectionlessBootstrap.handler(factory);
    connectionlessBootstrap.channel(OioDatagramChannel.class);
    ;
    datagramChannel =
        (DatagramChannel)
            connectionlessBootstrap.bind(new InetSocketAddress(mcastGroupPort)).sync().channel();
    multicastAddress = new InetSocketAddress(mcastGroupIp, mcastGroupPort);
    NetworkInterface networkInterface =
        NetworkInterface.getByInetAddress(InetAddress.getByName(bindAddress));
    // for (Enumeration nifs = NetworkInterface.getNetworkInterfaces();
    // nifs.hasMoreElements(); )
    datagramChannel.joinGroup(multicastAddress, null); // (NetworkInterface)
    // nifs.nextElement());
    init = true;
    if (debug) factory.debug();
  }
示例#6
0
 public void start() throws InterruptedException, URISyntaxException {
   EventLoopGroup group = new NioEventLoopGroup();
   try {
     Bootstrap b = new Bootstrap();
     b.group(group).channel(NioSocketChannel.class);
     b.handler(
         new ChannelInitializer<Channel>() {
           @Override
           protected void initChannel(Channel ch) throws Exception {
             ChannelPipeline pipeline = ch.pipeline();
             pipeline.addLast("decoder", new RtspResponseDecoder());
             pipeline.addLast("encoder", new RtspRequestEncoder());
             pipeline.addLast("aggregator", new HttpObjectAggregator(1024 * 1024 * 64));
             pipeline.addLast("handler", new ResponseHandler());
           }
         });
     b.option(ChannelOption.SO_KEEPALIVE, true);
     ChannelFuture channelFutrue = b.connect(host, port).sync();
     if (channelFutrue.isSuccess()) {
       channel = channelFutrue.channel();
       URI uri = new URI("rtsp://127.0.0.1:554/hello-world");
       HttpRequest request = this.buildOptionsRequest(uri.toASCIIString());
       this.send(request);
       channel.closeFuture().sync();
     }
   } finally {
     // 优雅退出,释放NIO线程组
     group.shutdownGracefully();
   }
 }
  @Override
  public void run() {

    EventLoopGroup group = new NioEventLoopGroup();

    try {

      Bootstrap b = new Bootstrap();

      b.group(group); // group 组
      b.channel(NioSocketChannel.class); // channel 通道
      b.option(ChannelOption.TCP_NODELAY, true); // option 选项
      b.handler(new ChildChannelHandler()); // handler 处理

      // 发起异步链接
      f = b.connect(BaseConfig.inetHost, BaseConfig.inetPort);

      // 等待客户端链路关闭
      f.channel().closeFuture().sync();

    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      group.shutdownGracefully();
    }
  }
示例#8
0
  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      System.out.println("usage: VisClient <server> <port>");
      System.exit(-1);
    }
    String serv = args[0];
    int port = Integer.parseInt(args[1]);

    PeerInfo server = new PeerInfo(serv, port);
    DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();

    // in case client acts as server, which is the reason behind a duplex
    // connection indeed.
    RpcServerCallExecutor executor = new ThreadPoolCallExecutor(3, 100);
    clientFactory.setRpcServerCallExecutor(executor);

    clientFactory.setConnectResponseTimeoutMillis(1000);

    // clientFactory.getRpcServiceRegistry().registerService();

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup());
    bootstrap.handler(clientFactory);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);

    RpcClientChannel channel = clientFactory.peerWith(server, bootstrap);

    BlockingInterface visService = ProtoFrame.FrameServerService.newBlockingStub(channel);
    RpcController cntr = channel.newRpcController();
    clientFactory
        .getRpcServiceRegistry()
        .registerService(
            ProtoFrame.FrameServerService.newReflectiveBlockingService(
                new BlockingVisServiceImpl(null, null)));

    new CASimVisClient(visService, cntr).run();
    //
    // channel.close();
    // executor.shutdown();
    // System.exit(0);
  }
示例#9
0
  @Override
  protected void serviceInit() throws Exception {
    final SslContext sslCtx;
    if (config.isSsl()) {
      sslCtx =
          SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
      sslCtx = null;
    }

    Class clazz;
    if (config.isUseEpoll()) {
      group = new EpollEventLoopGroup(config.getChildNioEventThreads());
      clazz = EpollSocketChannel.class;
    } else {
      group = new NioEventLoopGroup(config.getChildNioEventThreads());
      clazz = NioSocketChannel.class;
    }

    bootstrap = new Bootstrap();
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
    bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    bootstrap.option(ChannelOption.SO_LINGER, config.getSoLinger());
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
    bootstrap
        .group(group)
        .channel(clazz)
        .handler(
            new ChannelInitializer<SocketChannel>() {
              @Override
              public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                  p.addLast(sslCtx.newHandler(ch.alloc(), config.getHost(), config.getPort()));
                }
                p.addLast(
                    new MsgPackEncoder(),
                    new MsgPackDecoder(config.getPayload()),
                    new ClientHandler(ClientProxy.this));
              }
            });
  }
示例#10
0
 public void applyConnectionOptions(Bootstrap bootstrap) {
   bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);
   if (tcpSendBufferSize != -1) {
     bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
   }
   if (tcpReceiveBufferSize != -1) {
     bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
     bootstrap.option(
         ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(tcpReceiveBufferSize));
   }
   bootstrap.option(ChannelOption.SO_LINGER, soLinger);
   if (trafficClass != -1) {
     bootstrap.option(ChannelOption.IP_TOS, trafficClass);
   }
   bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
   bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
   bootstrap.option(ChannelOption.SO_KEEPALIVE, tcpKeepAlive);
 }
    public ClientChannelManager() {
      Bootstrap bootstrap = new Bootstrap();
      Class<? extends Channel> channelClass = m_descriptor.getChannelClass();

      bootstrap.group(m_descriptor.getGroup()).channel(channelClass);
      bootstrap.handler(new ClientChannelInitializer());

      for (Map.Entry<ChannelOption<Object>, Object> e : m_descriptor.getOptions().entrySet()) {
        bootstrap.option(e.getKey(), e.getValue());
      }

      m_bootstrap = bootstrap;
    }
示例#12
0
  private void setChannelFactory(final Bootstrap bootstrap, final KeyMapping keys) {
    if (keys != null && !keys.isEmpty()) {
      if (this.cf == null) {
        throw new UnsupportedOperationException(
            "No key access instance available, cannot use key mapping");
      }

      LOG.debug("Adding MD5 keys {} to boostrap {}", keys, bootstrap);
      bootstrap.channelFactory(this.cf);
      bootstrap.option(MD5ChannelOption.TCP_MD5SIG, keys);
    } else {
      bootstrap.channel(NioSocketChannel.class);
    }
  }
示例#13
0
  private ChannelHandlerContext connectRemoteServer() throws InterruptedException {
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      ClientChannelHandler channelHandler = new ClientChannelHandler(listener);
      Bootstrap b = new Bootstrap();
      b.group(workerGroup);
      b.channel(NioSocketChannel.class);
      b.option(ChannelOption.SO_KEEPALIVE, true);
      b.handler(channelHandler);

      ChannelFuture f = b.connect(getRemoteServer().getHost(), getRemoteServer().getPort()).sync();
      LOG.debug("connected to: " + this.getRemoteServer());
      return channelHandler.getCtx();
      // Wait until the connection is closed.
      // f.channel().closeFuture().sync();
    } finally {
      // workerGroup.shutdownGracefully();
    }
  }
示例#14
0
 /**
  * 初始化Bootstrap
  *
  * @return
  */
 public static final Bootstrap getBootstrap() {
   EventLoopGroup group = new NioEventLoopGroup();
   Bootstrap b = new Bootstrap();
   b.group(group).channel(NioSocketChannel.class);
   b.handler(
       new ChannelInitializer<Channel>() {
         @Override
         protected void initChannel(Channel ch) throws Exception {
           ChannelPipeline pipeline = ch.pipeline();
           pipeline.addLast(
               "frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
           pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
           pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
           pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
           pipeline.addLast("handler", new TcpClientHandler());
         }
       });
   b.option(ChannelOption.SO_KEEPALIVE, true);
   return b;
 }
  protected static Channel createAcceptorChannel(
      final ChannelType channelType,
      final InetSocketAddress localAddress,
      final MessageHandler handler) {
    final Bootstrap serverBootstrap = ServerUDPBootstrapFactory.createServerBootstrap(channelType);

    serverBootstrap
        .option(ChannelOption.SO_REUSEADDR, false)
        .handler(
            new ChannelInitializer<DatagramChannel>() {
              @Override
              protected void initChannel(final DatagramChannel ch) throws Exception {
                final ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("messageDecoder", handler);
                // pipeline.addLast("handler", serverHandler);
              }
            });

    try {

      ChannelFuture channelFuture =
          serverBootstrap.bind(new InetSocketAddress(localAddress.getPort())).sync();

      // channelFuture.channel().closeFuture().awaitUninterruptibly();//.awaitUninterruptibly();
      channelFuture.awaitUninterruptibly();
      if (channelFuture.isSuccess()) {
        return channelFuture.channel();

      } else {

      }
    } catch (InterruptedException e) {

      // eventLoopGroup.shutdownGracefully();
      // System.exit(-1);
    }
    return null;
  }
 @Override
 public HttpClient newInstance() {
   if (bootstrap == null) {
     bootstrap = new Bootstrap();
     bootstrap.option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.TCP_NODELAY, true);
     EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreads);
     bootstrap
         .group(workerGroup)
         .channel(NioSocketChannel.class)
         .handler(
             new ChannelInitializer<SocketChannel>() {
               @Override
               protected void initChannel(SocketChannel channel) throws Exception {
                 ChannelPipeline pipeline = channel.pipeline();
                 pipeline.addLast(new HttpClientCodec());
                 pipeline.addLast(new HttpContentDecompressor());
                 pipeline.addLast(new ChunkedWriteHandler());
                 pipeline.addLast(new HttpResponseDecoder());
                 pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
               }
             });
   }
   return new Netty4HttpClient(bootstrap);
 }
示例#17
0
 @Override
 public void start(Listener transportListener) {
   listener = Preconditions.checkNotNull(transportListener, "listener");
   Bootstrap b = new Bootstrap();
   b.group(group);
   b.channel(channelType);
   if (NioSocketChannel.class.isAssignableFrom(channelType)) {
     b.option(SO_KEEPALIVE, true);
   }
   /**
    * We don't use a ChannelInitializer in the client bootstrap because its "initChannel" method is
    * executed in the event loop and we need this handler to be in the pipeline immediately so that
    * it may begin buffering writes.
    */
   b.handler(negotiationHandler);
   // Start the connection operation to the server.
   channel =
       b.connect(address)
           .addListener(
               new ChannelFutureListener() {
                 @Override
                 public void operationComplete(ChannelFuture future) throws Exception {
                   if (!future.isSuccess()) {
                     ChannelHandlerContext ctx = channel.pipeline().context(handler);
                     if (ctx != null) {
                       // NettyClientHandler doesn't propagate exceptions, but the negotiator will
                       // need the
                       // exception to fail any writes. Note that this fires after handler, because
                       // it is as if
                       // handler was propagating the notification.
                       ctx.fireExceptionCaught(future.cause());
                     }
                     channel.pipeline().fireExceptionCaught(future.cause());
                   }
                 }
               })
           .channel();
   // Start the write queue as soon as the channel is constructed
   handler.startWriteQueue(channel);
   // This write will have no effect, yet it will only complete once the negotiationHandler
   // flushes any pending writes.
   channel
       .write(NettyClientHandler.NOOP_MESSAGE)
       .addListener(
           new ChannelFutureListener() {
             @Override
             public void operationComplete(ChannelFuture future) throws Exception {
               if (future.isSuccess()) {
                 listener.transportReady();
               } else {
                 // Need to notify of this failure, because handler.connectionError() is not
                 // guaranteed to
                 // have seen this cause.
                 notifyTerminated(Status.fromThrowable(future.cause()));
               }
             }
           });
   // Handle transport shutdown when the channel is closed.
   channel
       .closeFuture()
       .addListener(
           new ChannelFutureListener() {
             @Override
             public void operationComplete(ChannelFuture future) throws Exception {
               Status status = handler.errorStatus();
               if (status == null) {
                 // We really only expect this to happen if shutdown() was called, but in that case
                 // this
                 // status is ignored.
                 status = Status.INTERNAL.withDescription("Connection closed with unknown cause");
               }
               notifyTerminated(status);
             }
           });
 }
示例#18
0
  @Override
  public Future<PCEPSession> createClient(
      @Nonnull final InetSocketAddress remoteAddress,
      @Nonnull final long reconnectTime,
      @Nonnull final PCEPSessionListenerFactory listenerFactory,
      @Nonnull final PCEPSessionNegotiatorFactory negotiatorFactory,
      @Nonnull final KeyMapping keys,
      @Nullable final InetSocketAddress localAddress,
      @Nonnull final BigInteger dbVersion) {
    final Bootstrap b = new Bootstrap();
    b.group(this.workerGroup);
    b.localAddress(localAddress);
    setChannelFactory(b, keys);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
    final ReconnectStrategyFactory reconnectStrategy =
        reconnectTime == -1
            ? getNeverReconnectStrategyFactory()
            : getTimedReconnectStrategyFactory(reconnectTime);
    final PCCReconnectPromise promise =
        new PCCReconnectPromise(remoteAddress, reconnectStrategy, b);
    final ChannelInitializer<SocketChannel> channelInitializer =
        new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(final SocketChannel ch) throws Exception {
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getDecoders());
            ch.pipeline()
                .addLast(
                    "negotiator",
                    negotiatorFactory.getSessionNegotiator(
                        listenerFactory, ch, promise, new PCCPeerProposal(dbVersion)));
            ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getEncoders());
            ch.pipeline()
                .addLast(
                    new ChannelInboundHandlerAdapter() {
                      @Override
                      public void channelInactive(final ChannelHandlerContext ctx)
                          throws Exception {
                        if (promise.isCancelled()) {
                          return;
                        }

                        if (!promise.isInitialConnectFinished()) {
                          LOG.debug(
                              "Connection to {} was dropped during negotiation, reattempting",
                              remoteAddress);
                          return;
                        }
                        LOG.debug("Reconnecting after connection to {} was dropped", remoteAddress);
                        PCCDispatcherImpl.this.createClient(
                            remoteAddress,
                            reconnectTime,
                            listenerFactory,
                            negotiatorFactory,
                            keys,
                            localAddress,
                            dbVersion);
                      }
                    });
          }
        };
    b.handler(channelInitializer);
    promise.connect();
    return promise;
  }