Search in sources :

Example 66 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project spring-framework by spring-projects.

the class Netty4ClientHttpRequestFactory method buildBootstrap.

private Bootstrap buildBootstrap(URI uri, boolean isSecure) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            configureChannel(channel.config());
            ChannelPipeline pipeline = channel.pipeline();
            if (isSecure) {
                Assert.notNull(sslContext, "sslContext should not be null");
                pipeline.addLast(sslContext.newHandler(channel.alloc(), uri.getHost(), uri.getPort()));
            }
            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new HttpObjectAggregator(maxResponseSize));
            if (readTimeout > 0) {
                pipeline.addLast(new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
            }
        }
    });
    return bootstrap;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) Bootstrap(io.netty.bootstrap.Bootstrap) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 67 with Bootstrap

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

the class SimpleClient method establishConnection.

protected void establishConnection() throws IOException {
    // Configure the client.
    bootstrap = new Bootstrap().group(new NioEventLoopGroup()).channel(io.netty.channel.socket.nio.NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
    // Configure the pipeline factory.
    if (encryptionOptions.enabled) {
        bootstrap.handler(new SecureInitializer());
    } else {
        bootstrap.handler(new Initializer());
    }
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    channel = future.awaitUninterruptibly().channel();
    if (!future.isSuccess()) {
        bootstrap.group().shutdownGracefully();
        throw new IOException("Connection Error", future.cause());
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelInitializer(io.netty.channel.ChannelInitializer) InetSocketAddress(java.net.InetSocketAddress) Bootstrap(io.netty.bootstrap.Bootstrap) IOException(java.io.IOException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 68 with Bootstrap

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

the class NettyProducer method openConnection.

protected ChannelFuture openConnection() throws Exception {
    ChannelFuture answer;
    if (isTcp()) {
        // its okay to create a new bootstrap for each new channel
        Bootstrap clientBootstrap = new Bootstrap();
        if (configuration.isNativeTransport()) {
            clientBootstrap.channel(EpollSocketChannel.class);
        } else {
            clientBootstrap.channel(NioSocketChannel.class);
        }
        clientBootstrap.group(getWorkerGroup());
        clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
        clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
        clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
        clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
        //TODO need to check it later
        // set any additional netty options
        /*
            if (configuration.getOptions() != null) {
                for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
                    clientBootstrap.setOption(entry.getKey(), entry.getValue());
                }
            }*/
        // set the pipeline factory, which creates the pipeline for each newly created channels
        clientBootstrap.handler(pipelineFactory);
        answer = clientBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}", new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap });
        }
        return answer;
    } else {
        // its okay to create a new bootstrap for each new channel
        Bootstrap connectionlessClientBootstrap = new Bootstrap();
        if (configuration.isNativeTransport()) {
            connectionlessClientBootstrap.channel(EpollDatagramChannel.class);
        } else {
            connectionlessClientBootstrap.channel(NioDatagramChannel.class);
        }
        connectionlessClientBootstrap.group(getWorkerGroup());
        connectionlessClientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
        connectionlessClientBootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
        connectionlessClientBootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
        connectionlessClientBootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());
        //TODO need to check it later
        // set any additional netty options
        /*
            if (configuration.getOptions() != null) {
                for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
                    connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
                }
            }*/
        // set the pipeline factory, which creates the pipeline for each newly created channels
        connectionlessClientBootstrap.handler(pipelineFactory);
        // if no one is listen on the port
        if (!configuration.isUdpConnectionlessSending()) {
            answer = connectionlessClientBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        } else {
            // bind and store channel so we can close it when stopping
            answer = connectionlessClientBootstrap.bind(new InetSocketAddress(0)).sync();
            Channel channel = answer.channel();
            allChannels.add(channel);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new UDP client bootstrap connecting to {}:{} with options: {}", new Object[] { configuration.getHost(), configuration.getPort(), connectionlessClientBootstrap });
        }
        return answer;
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollDatagramChannel(io.netty.channel.epoll.EpollDatagramChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 69 with Bootstrap

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

the class SingleUDPNettyServerBootstrapFactory method startServerBootstrap.

protected void startServerBootstrap() throws Exception {
    // create non-shared worker pool
    EventLoopGroup wg = configuration.getWorkerGroup();
    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withNativeTransport(configuration.isNativeTransport()).withWorkerCount(configuration.getWorkerCount()).withName("NettyServerTCPWorker").build();
        wg = workerGroup;
    }
    Bootstrap bootstrap = new Bootstrap();
    if (configuration.isNativeTransport()) {
        bootstrap.group(wg).channel(EpollDatagramChannel.class);
    } else {
        bootstrap.group(wg).channel(NioDatagramChannel.class);
    }
    // We cannot set the child option here      
    bootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    bootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
    bootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());
    bootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
    // only set this if user has specified
    if (configuration.getReceiveBufferSizePredictor() > 0) {
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(configuration.getReceiveBufferSizePredictor()));
    }
    if (configuration.getBacklog() > 0) {
        bootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
    }
    Map<String, Object> options = configuration.getOptions();
    if (options != null) {
        for (Map.Entry<String, Object> entry : options.entrySet()) {
            String value = entry.getValue().toString();
            ChannelOption<Object> option = ChannelOption.valueOf(entry.getKey());
            //TODO: find a way to add primitive Netty options without having to add them to the Camel registry.
            if (EndpointHelper.isReferenceParameter(value)) {
                String name = value.substring(1);
                Object o = CamelContextHelper.mandatoryLookup(camelContext, name);
                bootstrap.option(option, o);
            } else {
                bootstrap.option(option, value);
            }
        }
    }
    LOG.debug("Created Bootstrap {}", bootstrap);
    // set the pipeline factory, which creates the pipeline for each newly created channels
    bootstrap.handler(pipelineFactory);
    InetSocketAddress hostAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    SubnetUtils multicastSubnet = new SubnetUtils(MULTICAST_SUBNET);
    if (multicastSubnet.getInfo().isInRange(configuration.getHost())) {
        ChannelFuture channelFuture = bootstrap.bind(configuration.getPort()).sync();
        channel = channelFuture.channel();
        DatagramChannel datagramChannel = (DatagramChannel) channel;
        String networkInterface = configuration.getNetworkInterface() == null ? LOOPBACK_INTERFACE : configuration.getNetworkInterface();
        multicastNetworkInterface = NetworkInterface.getByName(networkInterface);
        ObjectHelper.notNull(multicastNetworkInterface, "No network interface found for '" + networkInterface + "'.");
        LOG.info("ConnectionlessBootstrap joining {}:{} using network interface: {}", new Object[] { configuration.getHost(), configuration.getPort(), multicastNetworkInterface.getName() });
        datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly();
        allChannels.add(datagramChannel);
    } else {
        LOG.info("ConnectionlessBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
        ChannelFuture channelFuture = bootstrap.bind(hostAddress).sync();
        channel = channelFuture.channel();
        allChannels.add(channel);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SubnetUtils(org.apache.camel.component.netty4.util.SubnetUtils) InetSocketAddress(java.net.InetSocketAddress) EpollDatagramChannel(io.netty.channel.epoll.EpollDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) Bootstrap(io.netty.bootstrap.Bootstrap) Map(java.util.Map)

Example 70 with Bootstrap

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

the class NettyUDPByteArrayProviderTest 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 ByteArrayDecoder());
            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) ByteArrayDecoder(io.netty.handler.codec.bytes.ByteArrayDecoder)

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