Search in sources :

Example 76 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project async-http-client by AsyncHttpClient.

the class NettyRequestSender method sendRequestWithNewChannel.

private <//
T> //
ListenableFuture<T> sendRequestWithNewChannel(//
Request request, //
ProxyServer proxy, //
NettyResponseFuture<T> future, //
AsyncHandler<T> asyncHandler, boolean performingNextRequest) {
    // some headers are only set when performing the first request
    HttpHeaders headers = future.getNettyRequest().getHttpRequest().headers();
    Realm realm = future.getRealm();
    Realm proxyRealm = future.getProxyRealm();
    requestFactory.addAuthorizationHeader(headers, perConnectionAuthorizationHeader(request, proxy, realm));
    requestFactory.setProxyAuthorizationHeader(headers, perConnectionProxyAuthorizationHeader(request, proxyRealm));
    future.setInAuth(realm != null && realm.isUsePreemptiveAuth() && realm.getScheme() != AuthScheme.NTLM);
    future.setInProxyAuth(proxyRealm != null && proxyRealm.isUsePreemptiveAuth() && proxyRealm.getScheme() != AuthScheme.NTLM);
    // Do not throw an exception when we need an extra connection for a redirect
    // FIXME why? This violate the max connection per host handling, right?
    Bootstrap bootstrap = channelManager.getBootstrap(request.getUri(), proxy);
    Object partitionKey = future.getPartitionKey();
    // we disable channelPreemption when performing next requests
    final boolean acquireChannelLock = !performingNextRequest;
    try {
        // redirect.
        if (acquireChannelLock) {
            // if there's an exception here, channel wasn't preempted and resolve won't happen
            channelManager.acquireChannelLock(partitionKey);
        }
    } catch (Throwable t) {
        abort(null, future, getCause(t));
        // exit and don't try to resolve address
        return future;
    }
    scheduleRequestTimeout(future);
    //
    RequestHostnameResolver.INSTANCE.resolve(request, proxy, asyncHandler).addListener(new SimpleFutureListener<List<InetSocketAddress>>() {

        @Override
        protected void onSuccess(List<InetSocketAddress> addresses) {
            NettyConnectListener<T> connectListener = new NettyConnectListener<>(future, NettyRequestSender.this, channelManager, acquireChannelLock, partitionKey);
            NettyChannelConnector connector = new NettyChannelConnector(request.getLocalAddress(), addresses, asyncHandler, clientState, config);
            if (!future.isDone()) {
                connector.connect(bootstrap, connectListener);
            } else if (acquireChannelLock) {
                channelManager.releaseChannelLock(partitionKey);
            }
        }

        @Override
        protected void onFailure(Throwable cause) {
            if (acquireChannelLock) {
                channelManager.releaseChannelLock(partitionKey);
            }
            abort(null, future, getCause(cause));
        }
    });
    return future;
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) InetSocketAddress(java.net.InetSocketAddress) Bootstrap(io.netty.bootstrap.Bootstrap) List(java.util.List) NettyConnectListener(org.asynchttpclient.netty.channel.NettyConnectListener) Realm(org.asynchttpclient.Realm)

Example 77 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project pulsar by yahoo.

the class DiscoveryServiceTest method connectToService.

/**
     * creates ClientHandler channel to connect and communicate with server
     * 
     * @param serviceUrl
     * @param latch
     * @return
     * @throws URISyntaxException
     */
public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls) throws URISyntaxException {
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (tls) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                X509Certificate[] certificates = SecurityUtility.loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
                PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
                builder.keyManager(privateKey, (X509Certificate[]) certificates);
                SslContext sslCtx = builder.build();
                ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast(new ClientHandler(latch));
        }
    });
    URI uri = new URI(serviceUrl);
    InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    b.connect(serviceAddress).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            throw new IllegalStateException(future.cause());
        }
    });
    return workerGroup;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) PrivateKey(java.security.PrivateKey) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 78 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project cradle by BingLau7.

the class EchoClient method start.

void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // 指定 EventLoopGroup 以处理客户端时间;需要适用于 NIO 的实现
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port)).handler(new ChannelInitializer<SocketChannel>() {

            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new EchoClientHandler());
            }
        });
        // 连接远程节点,阻塞等待直到连接完成
        ChannelFuture f = b.connect().sync();
        // 阻塞,直到 Channel 关闭
        f.channel().closeFuture().sync();
    } finally {
        // 关闭线程池并释放所有的资源
        group.shutdownGracefully().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) InetSocketAddress(java.net.InetSocketAddress) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 79 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project Glowstone by GlowstoneMC.

the class HttpClient method connect.

public static void connect(String url, EventLoop eventLoop, HttpCallback callback) {
    URI uri = URI.create(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    SslContext sslCtx = null;
    if ("https".equalsIgnoreCase(scheme)) {
        if (port == -1)
            port = 443;
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (SSLException e) {
            callback.error(e);
            return;
        }
    } else if ("http".equalsIgnoreCase(scheme)) {
        if (port == -1)
            port = 80;
    } else {
        throw new IllegalArgumentException("Only http(s) is supported!");
    }
    new Bootstrap().group(eventLoop).resolver(resolverGroup).channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class).handler(new HttpChannelInitializer(sslCtx, callback)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).connect(InetSocketAddress.createUnresolved(host, port)).addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
            HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
            request.headers().set(HttpHeaderNames.HOST, host);
            future.channel().writeAndFlush(request);
        } else {
            callback.error(future.cause());
        }
    });
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SslContext(io.netty.handler.ssl.SslContext) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) InetSocketAddress(java.net.InetSocketAddress) EpollDatagramChannel(io.netty.channel.epoll.EpollDatagramChannel) Epoll(io.netty.channel.epoll.Epoll) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) io.netty.handler.codec.http(io.netty.handler.codec.http) SSLException(javax.net.ssl.SSLException) DnsServerAddresses(io.netty.resolver.dns.DnsServerAddresses) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) io.netty.channel(io.netty.channel) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) URI(java.net.URI) AllArgsConstructor(lombok.AllArgsConstructor) DnsAddressResolverGroup(io.netty.resolver.dns.DnsAddressResolverGroup) URI(java.net.URI) SSLException(javax.net.ssl.SSLException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SslContext(io.netty.handler.ssl.SslContext)

Example 80 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project aerospike-client-java by aerospike.

the class NettyCommand method executeCommand.

private void executeCommand() {
    try {
        Node node = command.getNode(cluster);
        conn = (NettyConnection) node.getAsyncConnection(eventState.index, null);
        if (conn != null) {
            InboundHandler handler = (InboundHandler) conn.channel.pipeline().last();
            handler.command = this;
            writeCommand();
            return;
        }
        try {
            final InboundHandler handler = new InboundHandler();
            handler.command = this;
            Bootstrap b = new Bootstrap();
            b.group(eventLoop.eventLoop);
            if (eventLoop.parent.isEpoll) {
                b.channel(EpollSocketChannel.class);
            } else {
                b.channel(NioSocketChannel.class);
            }
            b.option(ChannelOption.TCP_NODELAY, true);
            b.option(ChannelOption.AUTO_READ, false);
            b.handler(new ChannelInitializer<SocketChannel>() {

                @Override
                public void initChannel(SocketChannel ch) {
                    conn = new NettyConnection(ch, cluster.maxSocketIdleNanos);
                    ChannelPipeline p = ch.pipeline();
                    if (eventLoop.parent.sslContext != null) {
                        //InetSocketAddress address = node.getAddress();
                        //p.addLast(eventLoop.parent.sslContext.newHandler(ch.alloc(), address.getHostString(), address.getPort()));
                        p.addLast(eventLoop.parent.sslContext.newHandler(ch.alloc()));
                    }
                    p.addLast(handler);
                }
            });
            b.connect(node.getAddress());
        } catch (Exception e) {
            node.decrAsyncConnection(eventState.index);
            throw e;
        }
        eventState.errors = 0;
    } catch (AerospikeException.Connection ac) {
        eventState.errors++;
        onNetworkError(ac);
    } catch (Exception e) {
        // Fail without retry on unknown errors.
        eventState.errors++;
        fail();
        notifyFailure(new AerospikeException(e));
    }
}
Also used : AerospikeException(com.aerospike.client.AerospikeException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Node(com.aerospike.client.cluster.Node) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) AerospikeException(com.aerospike.client.AerospikeException) IOException(java.io.IOException)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)163 Channel (io.netty.channel.Channel)81 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)73 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)68 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)68 ChannelFuture (io.netty.channel.ChannelFuture)62 EventLoopGroup (io.netty.channel.EventLoopGroup)61 Test (org.junit.Test)61 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)49 InetSocketAddress (java.net.InetSocketAddress)49 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)37 SocketChannel (io.netty.channel.socket.SocketChannel)33 ChannelPipeline (io.netty.channel.ChannelPipeline)31 LocalAddress (io.netty.channel.local.LocalAddress)26 ClosedChannelException (java.nio.channels.ClosedChannelException)26 LocalChannel (io.netty.channel.local.LocalChannel)22 LocalServerChannel (io.netty.channel.local.LocalServerChannel)22 CountDownLatch (java.util.concurrent.CountDownLatch)22 ChannelFutureListener (io.netty.channel.ChannelFutureListener)20 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)18