Example usage for io.netty.bootstrap Bootstrap remoteAddress

List of usage examples for io.netty.bootstrap Bootstrap remoteAddress

Introduction

In this page you can find the example usage for io.netty.bootstrap Bootstrap remoteAddress.

Prototype

SocketAddress remoteAddress

To view the source code for io.netty.bootstrap Bootstrap remoteAddress.

Click Source Link

Usage

From source file:Http2Client.java

License:Apache License

public Http2Client(final String host, final int port, final boolean ssl) throws Exception {
    this.host = host;
    this.port = port;
    this.ssl = ssl;

    // Configure SSL.
    if (ssl) {/*from w  ww.  ja  va  2s  .  com*/
        this.sslCtx = SslContext.newClientContext(null, InsecureTrustManagerFactory.INSTANCE, null,
                Arrays.asList(SelectedProtocol.HTTP_2.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()),
                0, 0);
    } else {
        this.sslCtx = null;
    }

    // XXX (dano): Http2Connection does not seem to be thread safe, use one thread only
    this.workerGroup = new NioEventLoopGroup(1);
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx);

    // Configure the client.
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.remoteAddress(host, port);
    b.handler(initializer);

    // Start the client.
    this.channel = b.connect().syncUninterruptibly().channel();
    System.out.println("Connected to [" + host + ':' + port + ']');

    // Wait for the HTTP/2 upgrade to occur.
    this.connectionHandler = initializer.connectionHandler();
    connectionHandler.awaitInitialization();
}

From source file:alluxio.client.block.BlockStoreContext.java

License:Apache License

/**
 * Acquires a netty channel from the channel pools. If there is no available client instance
 * available in the pool, it tries to create a new one. And an exception is thrown if it fails to
 * create a new one./* w w  w  .  j av a 2  s  .  c om*/
 *
 * @param address the network address of the channel
 * @return the acquired netty channel
 * @throws IOException if it fails to create a new client instance mostly because it fails to
 *         connect to remote worker
 */
public static Channel acquireNettyChannel(final InetSocketAddress address) throws IOException {
    if (!NETTY_CHANNEL_POOL_MAP.containsKey(address)) {
        Bootstrap bs = NettyClient.createClientBootstrap();
        bs.remoteAddress(address);
        NettyChannelPool pool = new NettyChannelPool(bs,
                Configuration.getInt(PropertyKey.USER_NETWORK_NETTY_CHANNEL_POOL_SIZE_MAX),
                Configuration.getLong(PropertyKey.USER_NETWORK_NETTY_CHANNEL_POOL_GC_THRESHOLD_MS));
        if (NETTY_CHANNEL_POOL_MAP.putIfAbsent(address, pool) != null) {
            // This can happen if this function is called concurrently.
            pool.close();
        }
    }
    try {
        return NETTY_CHANNEL_POOL_MAP.get(address).acquire();
    } catch (InterruptedException e) {
        throw Throwables.propagate(e);
    }
}

From source file:alluxio.client.file.FileSystemContext.java

License:Apache License

/**
 * Acquires a netty channel from the channel pools. If there is no available client instance
 * available in the pool, it tries to create a new one. And an exception is thrown if it fails to
 * create a new one.// w  ww.  j av  a 2  s  .co m
 *
 * @param address the network address of the channel
 * @return the acquired netty channel
 * @throws IOException if it fails to create a new client instance mostly because it fails to
 *         connect to remote worker
 */
public Channel acquireNettyChannel(final InetSocketAddress address) throws IOException {
    if (!mNettyChannelPools.containsKey(address)) {
        Bootstrap bs = NettyClient.createClientBootstrap();
        bs.remoteAddress(address);
        NettyChannelPool pool = new NettyChannelPool(bs,
                Configuration.getInt(PropertyKey.USER_NETWORK_NETTY_CHANNEL_POOL_SIZE_MAX),
                Configuration.getLong(PropertyKey.USER_NETWORK_NETTY_CHANNEL_POOL_GC_THRESHOLD_MS));
        if (mNettyChannelPools.putIfAbsent(address, pool) != null) {
            // This can happen if this function is called concurrently.
            pool.close();
        }
    }
    try {
        return mNettyChannelPools.get(address).acquire();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:ccwihr.client.t2.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    //        // Configure SSL.
    //        final SslContext sslCtx;
    //        if (SSL) {
    //            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
    //            sslCtx = SslContextBuilder.forClient()
    //                .sslProvider(provider)
    //                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
    //                 * Please refer to the HTTP/2 specification for cipher requirements. */
    //                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
    //                .trustManager(InsecureTrustManagerFactory.INSTANCE)
    //                .applicationProtocolConfig(new ApplicationProtocolConfig(
    //                    Protocol.ALPN,
    //                    // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
    //                    SelectorFailureBehavior.NO_ADVERTISE,
    //                    // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
    //                    SelectedListenerFailureBehavior.ACCEPT,
    //                    ApplicationProtocolNames.HTTP_2,
    //                    ApplicationProtocolNames.HTTP_1_1))
    //                .build();
    //        } else {
    //            sslCtx = null;
    //        }//from w  w  w  .j ava 2s .  c om

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    //        Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);
    Http2ClientInitializer initializer = new Http2ClientInitializer(null, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
            streamId += 2;
        }
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.fjn.helper.frameworkex.netty.v4.echotest.EchoClient.java

License:Apache License

public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//  ww w . j  a v a  2  s.  c  o  m
        Bootstrap b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.remoteAddress(new InetSocketAddress(host, port));
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new EchoClientHandler());
            }
        });
        ChannelFuture f = (ChannelFuture) b.connect().sync();
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}

From source file:com.flysoloing.learning.network.netty.http2.helloworld.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  www .j  a  v  a  2  s.c o m
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.write(request), channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    wrappedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.write(request), channel.newPromise());
        }
        channel.flush();
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.flysoloing.learning.network.netty.spdy.client.SpdyClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.NPN,
                    // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectorFailureBehavior.NO_ADVERTISE,
                    // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.SPDY_3_1,
                    ApplicationProtocolNames.HTTP_1_1))
            .build();/*from  www.java  2s  .c  om*/

    HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to " + HOST + ':' + PORT);

        // Create a GET request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
        request.headers().set(HttpHeaderNames.HOST, HOST);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Send the GET request.
        channel.writeAndFlush(request).sync();

        // Waits for the complete HTTP response
        httpResponseHandler.queue().take().sync();
        System.out.println("Finished SPDY HTTP GET");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.hop.hhxx.example.http2.helloworld.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from ww  w.  ja  va  2s  . c om
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
            streamId += 2;
        }
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:com.springapp.mvc.netty.example.spdy.client.SpdyClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(/*from w  w  w .  j a v  a  2s .c  om*/
                    new ApplicationProtocolConfig(Protocol.NPN, SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL,
                            SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL,
                            SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()))
            .build();

    HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to " + HOST + ':' + PORT);

        // Create a GET request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "");
        request.headers().set(HttpHeaders.Names.HOST, HOST);
        request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        // Send the GET request.
        channel.writeAndFlush(request).sync();

        // Waits for the complete HTTP response
        httpResponseHandler.queue().take().sync();
        System.out.println("Finished SPDY HTTP GET");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }
}

From source file:eu.point.client.Client.java

License:Open Source License

/**
 * The method which creates the bootstrap to connect to the server.
 * It initializes the pipeline with all the required parameters and functions
 * for encoding, decoding, etc./*  w ww.  j  a  va2s.  co m*/
 * It then sends the message to the server.
 * If the message is a Resource Request, then it also returns the received Resource Offer.
 *
 * @param message The message to be sent.
 * @return The received Resource Offer in case the message was a Resource Request.
 */
public static TmSdnMessages.TmSdnMessage.ResourceOfferMessage sendMessage(TmSdnMessages.TmSdnMessage message) {
    EventLoopGroup group = new NioEventLoopGroup();
    TmSdnMessages.TmSdnMessage.ResourceOfferMessage resourceOffer = null;
    handler = new TmSdnClientHandler(message);
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, false);
        //initialize the pipeline
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();

                pipeline.addLast(new ProtobufVarint32FrameDecoder());
                pipeline.addLast(new ProtobufDecoder(TmSdnMessages.TmSdnMessage.getDefaultInstance()));
                pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
                pipeline.addLast(new ProtobufEncoder());
                pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(5));

                pipeline.addLast(handler);
            }
        });

        // Make a new connection.
        ChannelFuture f = b.remoteAddress(serverIP, tcpPort).connect();
        try {
            f.sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //if message is resource request, then get the received resource offer and return it.
        if (f.isSuccess() && message.getType() == TmSdnMessages.TmSdnMessage.TmSdnMessageType.RR) {
            TmSdnMessages.TmSdnMessage.ResourceOfferMessage resp = handler.resultQueue.take();
            if (resp != null) {
                resourceOffer = resp;
            }
        }
        //close the channel.
        f.channel().closeFuture().sync();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
    return resourceOffer;
}