Exemple #1
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();
    }
  }
  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();
  }
  @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());
          }
        });
  }
  @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);
          }
        }
      }
    };
  }
  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);
    }
  }
Exemple #7
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();
  }
Exemple #10
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();
    }
  }
Exemple #11
0
  public DefaultClient(
      Class channelClass, ChannelPipelineFactoryFactory factory, Set<String> channelOptions) {

    if (!Channel.class.isAssignableFrom(channelClass))
      throw new RuntimeException("serverChannelClass must implement ServerChannel");

    _factory = factory;
    if (factory instanceof ChannelPipelineFactoryBuilder)
      builder = (ChannelPipelineFactoryBuilder) factory;

    // Configure the client.
    bootstrap = new Bootstrap();

    if (isNio(channelClass)) {
      workerGroup = new NioEventLoopGroup();
    } else if (isOio(channelClass)) {
      workerGroup = new OioEventLoopGroup();
    } else {
      workerGroup = new LocalEventLoopGroup();
    }
    bootstrap.group(workerGroup);
    bootstrap.channel(channelClass);
    internalGroup = new DefaultEventExecutorGroup(10);
  }
  @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();
  }
Exemple #13
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());
            }
          }
        });
  }
 @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);
             }
           });
 }