Beispiel #1
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();
  }
Beispiel #2
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();
   }
 }
Beispiel #3
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();
    }
  }
  @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();
    }
  }
  public void initialize(String baseUrl, String username, String password)
      throws URISyntaxException {
    this.username = username;
    this.password = password;
    group = new NioEventLoopGroup();
    baseUri = new URI(baseUrl);
    String protocol = baseUri.getScheme();
    if (!"http".equals(protocol)) {
      throw new IllegalArgumentException("Unsupported protocol: " + protocol);
    }
    // Bootstrap is the factory for HTTP connections
    bootStrap = new Bootstrap();
    bootStrap.group(group);
    bootStrap.channel(NioSocketChannel.class);
    bootStrap.handler(
        new ChannelInitializer<SocketChannel>() {

          @Override
          public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("http-codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(MAX_HTTP_REQUEST_KB * 1024));
            pipeline.addLast("http-handler", new NettyHttpClientHandler());
          }
        });
  }
 public void testConnectTimeout(Bootstrap cb) throws Throwable {
   cb.handler(new TestHandler()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000);
   ChannelFuture future = cb.connect(BAD_HOST, BAD_PORT);
   try {
     assertThat(future.await(3000), is(true));
   } finally {
     future.channel().close();
   }
 }
  @Override
  public WsClientConnection connect(
      final HttpResponseHandler callback, final String url, final List<HttpParam> lParamQuery)
      throws RestException {
    Bootstrap wsBootStrap = new Bootstrap();
    wsBootStrap.group(group);
    wsBootStrap.channel(NioSocketChannel.class);
    wsBootStrap.handler(
        new ChannelInitializer<SocketChannel>() {

          @Override
          public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("http-codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(MAX_HTTP_REQUEST_KB * 1024));
            pipeline.addLast(
                "ws-handler", new NettyWSClientHandler(getWsHandshake(url, lParamQuery), callback));
          }
        });
    final ChannelFuture cf = wsBootStrap.connect(baseUri.getHost(), baseUri.getPort());
    cf.addListener(
        new ChannelFutureListener() {

          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
              callback.onChReadyToWrite();
              // Nothing - handshake future will activate later
              /*Channel ch = future.channel();
              NettyWSClientHandler handler = (NettyWSClientHandler) ch.pipeline().get("ws-handler");
              handler.handshakeFuture.sync();*/
            } else {
              callback.onFailure(future.cause());
            }
          }
        });
    // Provide disconnection handle to client
    return new WsClientConnection() {

      @Override
      public void disconnect() throws RestException {
        Channel ch = cf.channel();
        if (ch != null) {
          ch.writeAndFlush(new CloseWebSocketFrame());
          // NettyWSClientHandler will close the connection when the server
          // responds to the CloseWebSocketFrame.
          try {
            ch.closeFuture().sync();
          } catch (InterruptedException e) {
            throw new RestException(e);
          }
        }
      }
    };
  }
Beispiel #8
0
 public static ChannelFuture connect(PeerAddress peerAddress, byte[] hashinfo)
     throws InterruptedException {
   if (bootstrap == null) {
     init();
   }
   bootstrap.handler(HandlerFactory.client(hashinfo));
   ChannelFuture channelFuture =
       bootstrap.connect(peerAddress.getAddress(), peerAddress.getPort()).sync();
   register(peerAddress, channelFuture.channel());
   return channelFuture;
 }
  public void testSslRenegotiationRejected(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    reset();

    sb.childHandler(
        new ChannelInitializer<Channel>() {
          @Override
          @SuppressWarnings("deprecation")
          public void initChannel(Channel sch) throws Exception {
            serverChannel = sch;
            serverSslHandler = serverCtx.newHandler(sch.alloc());

            sch.pipeline().addLast("ssl", serverSslHandler);
            sch.pipeline().addLast("handler", serverHandler);
          }
        });

    cb.handler(
        new ChannelInitializer<Channel>() {
          @Override
          @SuppressWarnings("deprecation")
          public void initChannel(Channel sch) throws Exception {
            clientChannel = sch;
            clientSslHandler = clientCtx.newHandler(sch.alloc());

            sch.pipeline().addLast("ssl", clientSslHandler);
            sch.pipeline().addLast("handler", clientHandler);
          }
        });

    Channel sc = sb.bind().sync().channel();
    cb.connect().sync();

    Future<Channel> clientHandshakeFuture = clientSslHandler.handshakeFuture();
    clientHandshakeFuture.sync();

    String renegotiation = "SSL_RSA_WITH_RC4_128_SHA";
    clientSslHandler.engine().setEnabledCipherSuites(new String[] {renegotiation});
    clientSslHandler.renegotiate().await();
    serverChannel.close().awaitUninterruptibly();
    clientChannel.close().awaitUninterruptibly();
    sc.close().awaitUninterruptibly();
    try {
      if (serverException.get() != null) {
        throw serverException.get();
      }
      fail();
    } catch (DecoderException e) {
      assertTrue(e.getCause() instanceof SSLHandshakeException);
    }
    if (clientException.get() != null) {
      throw clientException.get();
    }
  }
    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;
    }
Beispiel #11
0
 public void start() throws Exception {
   bootstrap.handler(_factory.create(internalGroup, bootstrap));
   if (builder == null || !builder.hasReconnect()) _channel = connect();
   else
     while (_channel == null && !_stop)
       try {
         _channel = connect();
       } catch (Exception ex) {
         if (ex instanceof ConnectException) {
           System.out.println(ex);
           Thread.sleep(builder._reconnectTimeout);
         }
       }
 }
  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;
  }
 @Override
 protected void configureBootstrap(
     @NotNull Bootstrap bootstrap, @NotNull final Consumer<String> errorOutputConsumer) {
   bootstrap.handler(
       new ChannelInitializer() {
         @Override
         protected void initChannel(Channel channel) throws Exception {
           channel
               .pipeline()
               .addLast(
                   "fastCgiDecoder", new FastCgiDecoder(errorOutputConsumer, FastCgiService.this));
           channel.pipeline().addLast("exceptionHandler", ChannelExceptionHandler.getInstance());
         }
       });
 }
Beispiel #14
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);
  }
  private void bootstrapEnv(
      int dataCountDown, int settingsAckCount, int requestCountDown, int trailersCountDown)
      throws Exception {
    requestLatch = new CountDownLatch(requestCountDown);
    serverSettingsAckLatch = new CountDownLatch(settingsAckCount);
    dataLatch = new CountDownLatch(dataCountDown);
    trailersLatch = new CountDownLatch(trailersCountDown);
    sb = new ServerBootstrap();
    cb = new Bootstrap();

    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            serverFrameCountDown =
                new FrameCountDown(
                    serverListener, serverSettingsAckLatch, requestLatch, dataLatch, trailersLatch);
            p.addLast(new Http2ConnectionHandler(true, serverFrameCountDown));
          }
        });

    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    cb.handler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new Http2ConnectionHandler(false, clientListener));
          }
        });

    serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
    int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    http2Client = clientChannel.pipeline().get(Http2ConnectionHandler.class);
  }
  @Before
  public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);

    requestLatch = new CountDownLatch(1);
    frameWriter = new DefaultHttp2FrameWriter();
    dataCaptor = ArgumentCaptor.forClass(ByteBuf.class);

    sb = new ServerBootstrap();
    cb = new Bootstrap();

    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast("reader", new FrameAdapter(serverObserver));
            p.addLast(Http2CodecUtil.ignoreSettingsHandler());
          }
        });

    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    cb.handler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast("reader", new FrameAdapter(null));
            p.addLast(Http2CodecUtil.ignoreSettingsHandler());
          }
        });

    serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
    int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
  }
Beispiel #17
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;
 }
Beispiel #18
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();
    }
  }
  @Override
  public void start(final Environment env) throws IOException {
    LOG.trace(
        "Establishing internal connection to netconf server for client: {}", getClientAddress());

    final Bootstrap clientBootstrap = new Bootstrap();
    clientBootstrap.group(clientEventGroup).channel(LocalChannel.class);

    clientBootstrap.handler(
        new ChannelInitializer<LocalChannel>() {
          @Override
          public void initChannel(final LocalChannel ch) throws Exception {
            ch.pipeline()
                .addLast(
                    new SshProxyClientHandler(
                        in, out, netconfHelloMessageAdditionalHeader, callback));
          }
        });
    clientChannelFuture = clientBootstrap.connect(localAddress);
    clientChannelFuture.addListener(
        new GenericFutureListener<ChannelFuture>() {

          @Override
          public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
              clientChannel = clientChannelFuture.channel();
            } else {
              LOG.warn(
                  "Unable to establish internal connection to netconf server for client: {}",
                  getClientAddress());
              Preconditions.checkNotNull(callback, "Exit callback must be set");
              callback.onExit(
                  1,
                  "Unable to establish internal connection to netconf server for client: "
                      + getClientAddress());
            }
          }
        });
  }
  /**
   * Reconnect to the remote address that the closed channel was connected to. This creates a new
   * {@link ChannelPipeline} with the same handler instances contained in the old channel's
   * pipeline.
   *
   * @param timeout Timer task handle.
   * @throws Exception when reconnection fails.
   */
  @Override
  public void run(Timeout timeout) throws Exception {
    ChannelPipeline old = channel.pipeline();
    final CommandHandler<?, ?> handler = old.get(CommandHandler.class);
    final RedisAsyncConnection<?, ?> connection = old.get(RedisAsyncConnection.class);

    ChannelFuture connect = null;
    // TODO use better concurrent workaround
    synchronized (bootstrap) {
      connect =
          bootstrap
              .handler(
                  new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                      ch.pipeline().addLast(this, handler, connection);
                    }
                  })
              .connect();
    }
    connect.sync();
  }
  public void testConnectCancellation(Bootstrap cb) throws Throwable {
    cb.handler(new TestHandler()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    ChannelFuture future = cb.connect(BAD_HOST, BAD_PORT);
    try {
      if (future.await(1000)) {
        if (future.isSuccess()) {
          fail("A connection attempt to " + BAD_HOST + " must not succeed.");
        } else {
          throw future.cause();
        }
      }

      if (future.cancel(true)) {
        assertThat(future.channel().closeFuture().await(500), is(true));
        assertThat(future.isCancelled(), is(true));
      } else {
        // Cancellation not supported by the transport.
      }
    } finally {
      future.channel().close();
    }
  }
Beispiel #22
0
  public Fetcher(TajoConf conf, URI uri, FileChunk chunk) {
    this.uri = uri;
    this.fileChunk = chunk;
    this.useLocalFile = !chunk.fromRemote();
    this.state = TajoProtos.FetcherState.FETCH_INIT;
    this.conf = conf;

    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    this.host = uri.getHost() == null ? "localhost" : uri.getHost();
    this.port = uri.getPort();
    if (port == -1) {
      if (scheme.equalsIgnoreCase("http")) {
        this.port = 80;
      } else if (scheme.equalsIgnoreCase("https")) {
        this.port = 443;
      }
    }

    if (!useLocalFile) {
      bootstrap =
          new Bootstrap()
              .group(
                  NettyUtils.getSharedEventLoopGroup(
                      NettyUtils.GROUP.FETCHER,
                      conf.getIntVar(TajoConf.ConfVars.SHUFFLE_RPC_CLIENT_WORKER_THREAD_NUM)))
              .channel(NioSocketChannel.class)
              .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
              .option(
                  ChannelOption.CONNECT_TIMEOUT_MILLIS,
                  conf.getIntVar(TajoConf.ConfVars.SHUFFLE_FETCHER_CONNECT_TIMEOUT) * 1000)
              .option(ChannelOption.SO_RCVBUF, 1048576) // set 1M
              .option(ChannelOption.TCP_NODELAY, true);

      ChannelInitializer<Channel> initializer =
          new HttpClientChannelInitializer(fileChunk.getFile());
      bootstrap.handler(initializer);
    }
  }
  @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;
  }
  @Before
  public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);

    clientDelegator = null;
    serverDelegator = null;
    serverConnectedChannel = null;
    maxContentLength = 1024;
    setServerLatch(1);
    setClientLatch(1);
    frameWriter = new DefaultHttp2FrameWriter();

    sb = new ServerBootstrap();
    cb = new Bootstrap();

    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            Http2Connection connection = new DefaultHttp2Connection(true);
            p.addLast(
                "reader",
                new HttpAdapterFrameAdapter(
                    connection,
                    InboundHttp2ToHttpPriorityAdapter.newInstance(connection, maxContentLength),
                    new CountDownLatch(10)));
            serverDelegator = new HttpResponseDelegator(serverListener, serverLatch);
            p.addLast(serverDelegator);
            serverConnectedChannel = ch;
          }
        });

    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    cb.handler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            Http2Connection connection = new DefaultHttp2Connection(false);
            p.addLast(
                "reader",
                new HttpAdapterFrameAdapter(
                    connection,
                    InboundHttp2ToHttpPriorityAdapter.newInstance(connection, maxContentLength),
                    new CountDownLatch(10)));
            clientDelegator = new HttpResponseDelegator(clientListener, clientLatch);
            p.addLast(clientDelegator);
          }
        });

    serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
    int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
  }
  private static void testStringEcho(ServerBootstrap sb, Bootstrap cb, boolean autoRead)
      throws Throwable {
    final StringEchoHandler sh = new StringEchoHandler(autoRead);
    final StringEchoHandler ch = new StringEchoHandler(autoRead);

    sb.childHandler(
        new ChannelInitializer<SocketChannel>() {
          @Override
          public void initChannel(SocketChannel sch) throws Exception {
            sch.pipeline()
                .addLast("framer", new DelimiterBasedFrameDecoder(512, Delimiters.lineDelimiter()));
            sch.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.ISO_8859_1));
            sch.pipeline()
                .addBefore("decoder", "encoder", new StringEncoder(CharsetUtil.ISO_8859_1));
            sch.pipeline().addAfter("decoder", "handler", sh);
          }
        });

    cb.handler(
        new ChannelInitializer<SocketChannel>() {
          @Override
          public void initChannel(SocketChannel sch) throws Exception {
            sch.pipeline()
                .addLast("framer", new DelimiterBasedFrameDecoder(512, Delimiters.lineDelimiter()));
            sch.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.ISO_8859_1));
            sch.pipeline()
                .addBefore("decoder", "encoder", new StringEncoder(CharsetUtil.ISO_8859_1));
            sch.pipeline().addAfter("decoder", "handler", ch);
          }
        });

    Channel sc = sb.bind().sync().channel();
    Channel cc = cb.connect().sync().channel();
    for (String element : data) {
      String delimiter = random.nextBoolean() ? "\r\n" : "\n";
      cc.writeAndFlush(element + delimiter);
    }

    while (ch.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    while (sh.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }
    sh.channel.close().sync();
    ch.channel.close().sync();
    sc.close().sync();

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
      throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
      throw ch.exception.get();
    }
  }
 @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);
             }
           });
 }
Beispiel #27
0
  void internalConnect(
      final Handler<ClientConnection> connectHandler,
      final Handler<Throwable> connectErrorHandler) {

    if (bootstrap == null) {
      // Share the event loop thread to also serve the HttpClient's network traffic.
      VertxEventLoopGroup pool = new VertxEventLoopGroup();
      pool.addWorker(actualCtx.getEventLoop());
      bootstrap = new Bootstrap();
      bootstrap.group(pool);
      bootstrap.channel(NioSocketChannel.class);
      tcpHelper.checkSSL(vertx);

      bootstrap.handler(
          new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
              ChannelPipeline pipeline = ch.pipeline();
              pipeline.addLast("exceptionDispatcher", EXCEPTION_DISPATCH_HANDLER);

              if (tcpHelper.isSSL()) {
                SSLEngine engine = tcpHelper.getSSLContext().createSSLEngine(host, port);
                if (tcpHelper.isVerifyHost()) {
                  SSLParameters sslParameters = engine.getSSLParameters();
                  sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                  engine.setSSLParameters(sslParameters);
                }
                engine.setUseClientMode(true); // We are on the client side of the connection
                pipeline.addLast("ssl", new SslHandler(engine));
              }

              pipeline.addLast("codec", new HttpClientCodec());
              pipeline.addLast("handler", new ClientHandler());
            }
          });
    }
    tcpHelper.applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener(
        new ChannelFutureListener() {
          public void operationComplete(ChannelFuture channelFuture) throws Exception {
            final Channel ch = channelFuture.channel();
            if (channelFuture.isSuccess()) {
              if (tcpHelper.isSSL()) {
                // TCP connected, so now we must do the SSL handshake

                SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                Future<Channel> fut = sslHandler.handshakeFuture();
                fut.addListener(
                    new GenericFutureListener<Future<Channel>>() {
                      @Override
                      public void operationComplete(Future<Channel> future) throws Exception {
                        if (future.isSuccess()) {
                          connected(ch, connectHandler);
                        } else {
                          failed(
                              ch,
                              connectErrorHandler,
                              new SSLHandshakeException("Failed to create SSL connection"));
                        }
                      }
                    });
              } else {
                connected(ch, connectHandler);
              }
            } else {
              failed(ch, connectErrorHandler, channelFuture.cause());
            }
          }
        });
  }