Search in sources :

Example 71 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project camel by apache.

the class NettyUdpConnectedSendTest method createNettyUdpReceiver.

public void createNettyUdpReceiver() {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(new UdpHandler());
            channel.pipeline().addLast(new ContentHandler());
        }
    }).localAddress(new InetSocketAddress(getPort()));
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 72 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project apn-proxy by apn-proxy.

the class ApnProxyUserAgentForwardHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {
    final Channel uaChannel = uaChannelCtx.channel();
    final ApnProxyRemote apnProxyRemote = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();
    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        if (remoteChannel != null && remoteChannel.isActive()) {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Use old remote channel");
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {
            LoggerUtil.debug(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Create new remote channel");
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).option(ChannelOption.AUTO_READ, false).handler(new ApnProxyRemoteForwardChannelInitializer(uaChannel, this));
            // set local address
            if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
                bootstrap.localAddress(new InetSocketAddress((ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
            }
            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort());
            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);
            remoteConnectFuture.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));
                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);
                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {

                                    @Override
                                    public void operationComplete(ChannelFuture future) throws Exception {
                                        if (future.isSuccess()) {
                                            future.channel().read();
                                        }
                                    }
                                });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        LoggerUtil.error(logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Remote channel create fail");
                        // send error response
                        String errorMsg = "remote connect to " + uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote().getRemoteAddr() + " fail";
                        HttpMessage errorResponseMsg = HttpErrorUtil.buildHttpErrorMessage(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorMsg);
                        uaChannel.writeAndFlush(errorResponseMsg);
                        httpContentBuffer.clear();
                        future.channel().close();
                    }
                }
            });
        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        HttpContent hc = ((HttpContent) msg);
        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);
            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }
                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ApnProxyRemote(com.xx_dev.apn.proxy.remotechooser.ApnProxyRemote) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 73 with Bootstrap

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

the class NettyClientTransport method start.

@SuppressWarnings("unchecked")
@Override
public Runnable start(Listener transportListener) {
    lifecycleManager = new ClientTransportLifecycleManager(Preconditions.checkNotNull(transportListener, "listener"));
    handler = newHandler();
    HandlerSettings.setAutoWindow(handler);
    negotiationHandler = negotiator.newHandler(handler);
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(channelType);
    if (NioSocketChannel.class.isAssignableFrom(channelType)) {
        b.option(SO_KEEPALIVE, true);
    }
    for (Map.Entry<ChannelOption<?>, ?> entry : channelOptions.entrySet()) {
        // Every entry in the map is obtained from
        // NettyChannelBuilder#withOption(ChannelOption<T> option, T value)
        // so it is safe to pass the key-value pair to b.option().
        b.option((ChannelOption<Object>) entry.getKey(), entry.getValue());
    }
    /**
     * 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);
    channel = b.register().channel();
    // Start the connection operation to the server.
    channel.connect(address).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                ChannelHandlerContext ctx = future.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());
                }
                future.channel().pipeline().fireExceptionCaught(future.cause());
            }
        }
    });
    // 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()) {
                // Need to notify of this failure, because NettyClientHandler may not have been added to
                // the pipeline before the error occurred.
                lifecycleManager.notifyTerminated(Utils.statusFromThrowable(future.cause()));
            }
        }
    });
    // Handle transport shutdown when the channel is closed.
    channel.closeFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            // Typically we should have noticed shutdown before this point.
            lifecycleManager.notifyTerminated(Status.INTERNAL.withDescription("Connection closed with unknown cause"));
        }
    });
    if (enableKeepAlive) {
        keepAliveManager = new KeepAliveManager(this, channel.eventLoop(), keepAliveDelayNanos, keepAliveTimeoutNanos, false);
        keepAliveManager.onTransportStarted();
    }
    return null;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelOption(io.netty.channel.ChannelOption) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) KeepAliveManager(io.grpc.internal.KeepAliveManager) Map(java.util.Map) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Http2ChannelClosedException(io.netty.handler.codec.http2.StreamBufferingEncoder.Http2ChannelClosedException) ClosedChannelException(java.nio.channels.ClosedChannelException)

Example 74 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project riposte by Nike-Inc.

the class StreamingAsyncHttpClient method generateClientBootstrap.

protected Bootstrap generateClientBootstrap(EventLoopGroup eventLoopGroup, Class<? extends SocketChannel> channelClass) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup).channel(channelClass);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, downstreamConnectionTimeoutMillis);
    return bootstrap;
}
Also used : Bootstrap(io.netty.bootstrap.Bootstrap)

Example 75 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project alluxio by Alluxio.

the class RPCMessageIntegrationTest method beforeClass.

@BeforeClass
public static void beforeClass() {
    sEventClient = new NioEventLoopGroup(1);
    sEventServer = new NioEventLoopGroup(1);
    sIncomingHandler = new MessageSavingHandler();
    // Setup the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(sEventServer);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new PipelineInitializer(sIncomingHandler));
    InetSocketAddress address = new InetSocketAddress(NetworkAddressUtils.getLocalHostName(100), Integer.parseInt(PropertyKey.MASTER_RPC_PORT.getDefaultValue()));
    ChannelFuture cf = bootstrap.bind(address).syncUninterruptibly();
    sLocalAddress = cf.channel().localAddress();
    // Setup the client.
    sBootstrapClient = new Bootstrap();
    sBootstrapClient.group(sEventClient);
    sBootstrapClient.channel(NioSocketChannel.class);
    sBootstrapClient.handler(new PipelineInitializer(new MessageSavingHandler()));
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) BeforeClass(org.junit.BeforeClass)

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