Example usage for io.netty.channel FixedRecvByteBufAllocator FixedRecvByteBufAllocator

List of usage examples for io.netty.channel FixedRecvByteBufAllocator FixedRecvByteBufAllocator

Introduction

In this page you can find the example usage for io.netty.channel FixedRecvByteBufAllocator FixedRecvByteBufAllocator.

Prototype

public FixedRecvByteBufAllocator(int bufferSize) 

Source Link

Document

Creates a new predictor that always returns the same prediction of the specified buffer size.

Usage

From source file:org.restcomm.imscf.common.lwcomm.service.impl.LwCommListener.java

License:Open Source License

void start() {
    // TODO: handle AS-resolved pools
    int receiveTransportThreads = config.getReceiveTransportPoolConfig().getMaxThreads();
    int receiveWorkerThreads = config.getReceiveWorkerPoolConfig().getMaxThreads();

    // Netty 4.0 does not handle parallel UDP servers well.
    // See: https://github.com/netty/netty/issues/1706
    // We differentiate two listener modes:
    //// w  w  w . ja  v a  2 s  .c om
    // a) NIO
    // ------
    // In this case a simple NioEventLoopGroup is used. The NioEventLoopGroup is given
    // "receiveTransportThreads" number of threads. User listener will be called
    // in a different executor which has receiveWorkerThreads number of threads.
    // This does not work well with netty 4.0 but still implemented here
    // in case of it will be fixed in a future netty version (the problem is
    // that regardless of setting the nThreads parameter in NioEventLoopGroup only
    // one thread is used for incoming packet processing...).
    //
    // c) EPOLL
    // --------
    // The solution offered in the link above:
    // 1) Use the epoll transport (Linux only)
    // 2) Turn on SO_REUSEPORT option
    // 3) Create multiple datagram channels bound to the same port
    // According to this: http://stackoverflow.com/questions/3261965/so-reuseport-on-linux
    // only works on Linux with kernel 3.9+ or RHEL 6.5+ -- if epoll is not available,
    // it falls back to NIO mode.

    LwCommServiceImpl.LOGGER.info(
            "Starting LwCommListener. Receive transport threads: {}, receive worker threads: {}",
            receiveTransportThreads, receiveWorkerThreads);
    Configuration.ListenerMode listenerMode = config.getListenerMode();
    LwCommServiceImpl.LOGGER.info("Listener mode configured is {}", config.getListenerMode());
    if (listenerMode == Configuration.ListenerMode.EPOLL && !Epoll.isAvailable()) {
        LwCommServiceImpl.LOGGER
                .warn("Listener mode EPOLL is configured but is not available. Falling back to NIO mode.");
        listenerMode = Configuration.ListenerMode.NIO;
    }
    Bootstrap b = new Bootstrap();

    b.group(receiveTransportGroup);
    if (receiveTransportGroup instanceof EpollEventLoopGroup) {
        b.channel(EpollDatagramChannel.class);
        b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        b.option(EpollChannelOption.SO_REUSEPORT, true);
    } else {
        b.channel(NioDatagramChannel.class);
        b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }
    channels = new HashSet<Channel>();
    b.handler(new ChannelInitializer<DatagramChannel>() {
        protected void initChannel(DatagramChannel channel) throws Exception {
            LwCommServiceImpl.LOGGER.info("Initializing channel: '{}'", channel);
            channels.add(channel);
            channel.pipeline().addLast(channelHandler);
        }
    });
    // TODO FIXME: hardcoded 256K limit for receive buffer!
    b.option(ChannelOption.SO_RCVBUF, 256 * 1024);
    b.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(10240));

    InetAddress host = null;
    int port = config.getLocalNode().getPort();
    try {
        host = InetAddress.getByName(config.getLocalNode().getHost());
        ChannelFuture future;
        if (listenerMode == ListenerMode.NIO) {
            future = b.bind(host, port).sync();
            if (!future.isSuccess()) {
                LwCommServiceImpl.LOGGER.error("Error while binding socket to {}:{}", host, port);
            } else {
                LwCommServiceImpl.LOGGER.info("Binding socket to {}:{} - SUCCESS", host, port);
            }
        } else {
            for (int i = 0; i < receiveTransportThreads; i++) {
                future = b.bind(host, port).sync();
                if (!future.isSuccess()) {
                    LwCommServiceImpl.LOGGER.error("Error while binding {} of {} socket to {}:{}", i + 1,
                            receiveTransportThreads, host, port);
                } else {
                    LwCommServiceImpl.LOGGER.info("Successfully bound socket {} of {} to {}:{} - ", i + 1,
                            receiveTransportThreads, host, port, future.channel());
                }
            }
        }
    } catch (Exception e) {
        LwCommServiceImpl.LOGGER.error("Error while binding socket or getting local node address.", e);
    }
}

From source file:org.vertx.java.core.net.impl.TCPSSLHelper.java

License:Open Source License

public void applyConnectionOptions(ServerBootstrap bootstrap) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpSendBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }//from  w  w  w  .ja  va2  s .c o  m
    if (tcpReceiveBufferSize != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(tcpReceiveBufferSize));
    }

    bootstrap.option(ChannelOption.SO_LINGER, soLinger);
    if (trafficClass != -1) {
        bootstrap.childOption(ChannelOption.IP_TOS, trafficClass);
    }
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, tcpKeepAlive);
    bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    bootstrap.option(ChannelOption.SO_BACKLOG, acceptBackLog);
}

From source file:org.vertx.java.core.net.impl.TCPSSLHelper.java

License:Open Source License

public void applyConnectionOptions(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpSendBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }//w  w  w .j  av a2s .com
    if (tcpReceiveBufferSize != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(tcpReceiveBufferSize));
    }
    bootstrap.option(ChannelOption.SO_LINGER, soLinger);
    if (trafficClass != -1) {
        bootstrap.option(ChannelOption.IP_TOS, trafficClass);
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, tcpKeepAlive);
}

From source file:ratpack.server.internal.DefaultRatpackServer.java

License:Apache License

protected Channel buildChannel(final ServerConfig serverConfig, final ChannelHandler handlerAdapter)
        throws InterruptedException {

    SslContext sslContext = serverConfig.getNettySslContext();
    this.useSsl = sslContext != null;

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverConfig.getConnectTimeoutMillis().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
        serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
    });/*from  w w w. jav  a  2 s  .c om*/
    serverConfig.getMaxMessagesPerRead().ifPresent(i -> {
        FixedRecvByteBufAllocator allocator = new FixedRecvByteBufAllocator(i);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, allocator);
        serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, allocator);
    });
    serverConfig.getReceiveBufferSize().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.SO_RCVBUF, i);
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, i);
    });
    serverConfig.getWriteSpinCount().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.WRITE_SPIN_COUNT, i);
        serverBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, i);
    });
    serverConfig.getConnectQueueSize().ifPresent(i -> serverBootstrap.option(ChannelOption.SO_BACKLOG, i));

    return serverBootstrap.group(execController.getEventLoopGroup())
            .channel(ChannelImplDetector.getServerSocketChannelImpl())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    new ConnectionIdleTimeout(pipeline, serverConfig.getIdleTimeout());

                    if (sslContext != null) {
                        SSLEngine sslEngine = sslContext.newEngine(PooledByteBufAllocator.DEFAULT);
                        pipeline.addLast("ssl", new SslHandler(sslEngine));
                    }

                    pipeline.addLast("decoder", new HttpRequestDecoder(serverConfig.getMaxInitialLineLength(),
                            serverConfig.getMaxHeaderSize(), serverConfig.getMaxChunkSize(), false));
                    pipeline.addLast("encoder", new HttpResponseEncoder());
                    pipeline.addLast("deflater", new IgnorableHttpContentCompressor());
                    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
                    pipeline.addLast("adapter", handlerAdapter);

                    ch.config().setAutoRead(false);
                }
            }).bind(buildSocketAddress(serverConfig)).sync().channel();
}

From source file:se.sics.gvod.net.NettyNetwork.java

License:Open Source License

/**
 * Start listening as a server at the given address..
 *
 * @param addr the address to listen at//  w  ww  .j a v a  2s  .c  o  m
 * @param port the port number to listen at
 * @param bindAllNetworkIfs whether to bind on all network interfaces
 * @return true if listening was started
 * @throws ChannelException in case binding failed
 */
private boolean bindUdpPort(final InetAddress addr, final int port, final boolean bindAllNetworkIfs) {

    if (udpPortsToSockets.containsKey(port)) {
        return true;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class)
            .handler(new NettyMsgHandler(component, Transport.UDP, msgDecoderClass));

    // Allow packets as large as up to 1600 bytes (default is 768).
    // You could increase or decrease this value to avoid truncated packets
    // or to improve memory footprint respectively.
    //
    // Please also note that a large UDP packet might be truncated or
    // dropped by your router no matter how you configured this option.
    // In UDP, a packet is truncated or dropped if it is larger than a
    // certain size, depending on router configuration. IPv4 routers
    // truncate and IPv6 routers drop a large packet. That's why it is
    // safe to send small packets in UDP.
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1500));
    bootstrap.option(ChannelOption.SO_RCVBUF, RECV_BUFFER_SIZE);

    bootstrap.option(ChannelOption.SO_SNDBUF, SEND_BUFFER_SIZE);
    // bootstrap.setOption("trafficClass", trafficClass);
    // bootstrap.setOption("soTimeout", soTimeout);
    // bootstrap.setOption("broadcast", broadcast);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);

    try {
        DatagramChannel c;
        if (bindAllNetworkIfs) {
            c = (DatagramChannel) bootstrap.bind(
                    //                        new InetSocketAddress(port)
                    port).sync().channel();
        } else {
            c = (DatagramChannel) bootstrap.bind(new InetSocketAddress(addr, port)).sync().channel();
        }

        addLocalSocket(new InetSocketAddress(addr, port), c);
        logger.debug("Successfully bound to ip:port {}:{}", addr, port);
    } catch (InterruptedException e) {
        logger.warn("Problem when trying to bind to {}:{}", addr.getHostAddress(), port);
        trigger(new Fault(e.getCause()), control);
        return false;
    }

    udpSocketsToBootstraps.put(new InetSocketAddress(addr, port), bootstrap);

    return true;
}