Example usage for io.netty.channel ChannelOption RCVBUF_ALLOCATOR

List of usage examples for io.netty.channel ChannelOption RCVBUF_ALLOCATOR

Introduction

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

Prototype

ChannelOption RCVBUF_ALLOCATOR

To view the source code for io.netty.channel ChannelOption RCVBUF_ALLOCATOR.

Click Source Link

Usage

From source file:com.caocao.nio.server.NettyServer.java

License:Apache License

public void initAndStart() {
    System.out.println("port:" + port);
    // Configure the server.
    bossGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
    workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
    try {/*from w  ww  . j  a  v  a 2 s  . c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, 5 * 1024)
                .option(ChannelOption.SO_SNDBUF, 5 * 1024)
                .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(40, 64, 1024))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new CustomerInitializer());

        // Start the server.
        ChannelFuture f = b.bind(port).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("netty??", e);
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.codebroker.core.service.NettyNetService.java

License:Open Source License

@Override
public void init(Object object) {
    logger.info("?Netty ");
    PropertiesWrapper propertiesWrapper = (PropertiesWrapper) object;

    int defaultValue = Runtime.getRuntime().availableProcessors() * 2;

    bossGroupNum = propertiesWrapper.getIntProperty(SystemEnvironment.NETTY_BOSS_GROUP_NUM, defaultValue);
    workerGroupNum = propertiesWrapper.getIntProperty(SystemEnvironment.NETTY_WORKER_GROUP_NUM, defaultValue);
    backlog = propertiesWrapper.getIntProperty(SystemEnvironment.NETTY_BACKLOG, BACKLOG);

    name = propertiesWrapper.getProperty(SystemEnvironment.NETTY_SERVER_NAME, "NETTY_SERVER");
    int port = propertiesWrapper.getIntProperty(SystemEnvironment.TCP_PROT, D_PORT);
    Thread thread = new Thread(new Runnable() {
        public void run() {
            bootstrap = new ServerBootstrap();
            bossGroup = new NioEventLoopGroup(bossGroupNum);
            workerGroup = new NioEventLoopGroup(workerGroupNum);
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, backlog)
                    .option(ChannelOption.SO_REUSEADDR, Boolean.valueOf(true))
                    // .option(ChannelOption.TCP_NODELAY,
                    // Boolean.valueOf(true))
                    // .option(ChannelOption.SO_KEEPALIVE,
                    // Boolean.valueOf(true))
                    .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childOption(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
                    .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new NettyServerInitializer());
            ChannelFuture f;/* w w  w.j  a v a 2s.co m*/
            try {
                f = bootstrap.bind(port).sync();
                f.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }, "Netty-Start-Thread");
    thread.start();
    logger.info("?Netty ?");
    super.setActive();
}

From source file:com.corundumstudio.socketio.SocketIOServer.java

License:Apache License

protected void applyConnectionOptions(ServerBootstrap bootstrap) {
    SocketConfig config = configCopy.getSocketConfig();
    bootstrap.childOption(ChannelOption.TCP_NODELAY, config.isTcpNoDelay());
    if (config.getTcpSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize());
    }//from  w  w w .  ja  v a2s .com
    if (config.getTcpReceiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, config.getTcpReceiveBufferSize());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(config.getTcpReceiveBufferSize()));
    }
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive());

    bootstrap.option(ChannelOption.SO_LINGER, config.getSoLinger());
    bootstrap.option(ChannelOption.SO_REUSEADDR, config.isReuseAddress());
    bootstrap.option(ChannelOption.SO_BACKLOG, config.getAcceptBackLog());
}

From source file:com.heliosapm.streams.metrichub.HubManager.java

License:Apache License

private HubManager(final Properties properties) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                close();// w  w  w  .ja  va2s .  c om
            } catch (Exception x) {
                /* No Op */}
        }
    });
    log.info(">>>>> Initializing HubManager...");
    metricMetaService = new MetricsMetaAPIImpl(properties);
    tsdbEndpoint = TSDBEndpoint.getEndpoint(metricMetaService.getSqlWorker());
    for (String url : tsdbEndpoint.getUpServers()) {
        final URL tsdbUrl = URLHelper.toURL(url);
        tsdbAddresses.add(new InetSocketAddress(tsdbUrl.getHost(), tsdbUrl.getPort()));
    }
    endpointCount = tsdbAddresses.size();
    endpointSequence = new AtomicInteger(endpointCount);
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2,
            metricMetaService.getForkJoinPool());
    bootstrap = new Bootstrap();
    bootstrap.handler(channelInitializer).group(group).channel(NioSocketChannel.class)
            .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator())
            .option(ChannelOption.ALLOCATOR, BufferManager.getInstance());
    final ChannelPoolHandler poolHandler = this;
    poolMap = new AbstractChannelPoolMap<InetSocketAddress, SimpleChannelPool>() {
        @Override
        protected SimpleChannelPool newPool(final InetSocketAddress key) {
            final Bootstrap b = new Bootstrap().handler(channelInitializer).group(group).remoteAddress(key)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator())
                    .option(ChannelOption.ALLOCATOR, BufferManager.getInstance());
            return new SimpleChannelPool(b, poolHandler);
        }
    };
    eventExecutor = new DefaultEventExecutor(metricMetaService.getForkJoinPool());
    channelGroup = new DefaultChannelGroup("MetricHubChannelGroup", eventExecutor);

    //      tsdbAddresses.parallelStream().forEach(addr -> {
    //         final Set<Channel> channels = Collections.synchronizedSet(new HashSet<Channel>(3));
    //         IntStream.of(1,2,3).parallel().forEach(i -> {
    //            final ChannelPool pool = poolMap.get(addr); 
    //            try {channels.add(pool.acquire().awaitUninterruptibly().get());
    //            } catch (Exception e) {}
    //            log.info("Acquired [{}] Channels", channels.size());
    //            channels.parallelStream().forEach(ch -> pool.release(ch));
    //         });
    //      });

    log.info("<<<<< HubManager Initialized.");
}

From source file:com.ibasco.agql.protocols.valve.source.query.SourceQueryMessenger.java

License:Open Source License

@Override
protected Transport<SourceServerRequest> createTransportService() {
    NettyPooledUdpTransport<SourceServerRequest> transport = new NettyPooledUdpTransport<>(ChannelType.NIO_UDP);
    transport.setChannelInitializer(new SourceQueryChannelInitializer(this));
    transport.addChannelOption(ChannelOption.SO_SNDBUF, 1048576);
    transport.addChannelOption(ChannelOption.SO_RCVBUF, 1048576);
    transport.addChannelOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1400));
    return transport;
}

From source file:com.jfastnet.peers.netty.KryoNettyPeer.java

License:Apache License

@Override
public boolean start() {
    group = new NioEventLoopGroup();
    try {//from  w  w w  .  j  a va2s.  c  o m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_SNDBUF, config.socketSendBufferSize)
                .option(ChannelOption.SO_RCVBUF, config.socketReceiveBufferSize)
                .option(ChannelOption.RCVBUF_ALLOCATOR,
                        new FixedRecvByteBufAllocator(config.receiveBufferAllocator))
                .handler(channelHandler != null ? channelHandler : new UdpHandler());

        channel = b.bind(config.bindPort).sync().channel();

    } catch (Exception e) {
        log.error("Couldn't start server.", e);
        return false;
    }
    return true;
}

From source file:com.mc.netty.server.NettyServer.java

License:Open Source License

private ServerBootstrap getDefaultServerBootstrap() {
    ServerBootstrap bootStrap = new ServerBootstrap();
    bootStrap.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 1000)
            // ???
            .option(ChannelOption.SO_SNDBUF, 32 * 1024).option(ChannelOption.SO_RCVBUF, 32 * 1024)
            .option(ChannelOption.TCP_NODELAY, true)
            // ???
            .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
            .channel(NioServerSocketChannel.class).childOption(ChannelOption.SO_KEEPALIVE, true);

    return bootStrap;
}

From source file:com.yahoo.pulsar.broker.service.BrokerService.java

License:Apache License

public void start() throws Exception {
    this.producerNameGenerator = new DistributedIdGenerator(pulsar.getZkClient(), producerNameGeneratorPath,
            pulsar.getConfiguration().getClusterName());

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.group(acceptorGroup, workerGroup);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
            new AdaptiveRecvByteBufAllocator(1024, 16 * 1024, 1 * 1024 * 1024));

    if (workerGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollServerSocketChannel.class);
        bootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {/*from  w  w  w  .j a  va  2s  .  c o  m*/
        bootstrap.channel(NioServerSocketChannel.class);
    }

    ServiceConfiguration serviceConfig = pulsar.getConfiguration();

    bootstrap.childHandler(new PulsarChannelInitializer(this, serviceConfig, false));
    // Bind and start to accept incoming connections.
    bootstrap.bind(new InetSocketAddress(pulsar.getBindAddress(), port)).sync();
    log.info("Started Pulsar Broker service on port {}", port);

    if (serviceConfig.isTlsEnabled()) {
        ServerBootstrap tlsBootstrap = bootstrap.clone();
        tlsBootstrap.childHandler(new PulsarChannelInitializer(this, serviceConfig, true));
        tlsBootstrap.bind(new InetSocketAddress(pulsar.getBindAddress(), tlsPort)).sync();
        log.info("Started Pulsar Broker TLS service on port {}", tlsPort);
    }

    // start other housekeeping functions
    this.startStatsUpdater();
    this.startInactivityMonitor();
    this.startMessageExpiryMonitor();
    this.startBacklogQuotaChecker();
}

From source file:com.yahoo.pulsar.discovery.service.DiscoveryService.java

License:Apache License

/**
 * starts server to handle discovery-request from client-channel
 * /*from  ww w  .  j  a va2 s .co  m*/
 * @throws Exception
 */
public void startServer() throws Exception {

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.group(acceptorGroup, workerGroup);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
            new AdaptiveRecvByteBufAllocator(1024, 16 * 1024, 1 * 1024 * 1024));

    if (workerGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollServerSocketChannel.class);
        bootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {
        bootstrap.channel(NioServerSocketChannel.class);
    }

    bootstrap.childHandler(new ServiceChannelInitializer(this, config, false));
    // Bind and start to accept incoming connections.
    bootstrap.bind(config.getServicePort()).sync();
    LOG.info("Started Pulsar Broker service on port {}", config.getWebServicePort());

    if (config.isTlsEnabled()) {
        ServerBootstrap tlsBootstrap = bootstrap.clone();
        tlsBootstrap.childHandler(new ServiceChannelInitializer(this, config, true));
        tlsBootstrap.bind(config.getServicePortTls()).sync();
        LOG.info("Started Pulsar Broker TLS service on port {}", config.getWebServicePortTls());
    }
}

From source file:dorkbox.network.Client.java

License:Apache License

/**
 * Starts a REMOTE <b>only</b> client, which will connect to the specified host using the specified Connections Options
 *///from w  w w .j  ava2s.co  m
@SuppressWarnings("AutoBoxing")
public Client(final Configuration config) throws SecurityException {
    super(config);

    String threadName = Client.class.getSimpleName();

    this.config = config;
    boolean hostConfigured = (config.tcpPort > 0 || config.udpPort > 0) && config.host != null;
    boolean isLocalChannel = config.localChannelName != null;

    if (isLocalChannel && hostConfigured) {
        String msg = threadName
                + " Local channel use and TCP/UDP use are MUTUALLY exclusive. Unable to determine what to do.";
        logger.error(msg);
        throw new IllegalArgumentException(msg);
    }

    localChannelName = config.localChannelName;
    hostName = config.host;

    Bootstrap localBootstrap = null;
    Bootstrap tcpBootstrap = null;
    Bootstrap udpBootstrap = null;

    if (config.localChannelName != null) {
        localBootstrap = new Bootstrap();
    }

    if (config.tcpPort > 0 || config.udpPort > 0) {
        if (config.host == null) {
            throw new IllegalArgumentException("You must define what host you want to connect to.");
        }

        if (config.host.equals("0.0.0.0")) {
            throw new IllegalArgumentException(
                    "You cannot connect to 0.0.0.0, you must define what host you want to connect to.");
        }
    }

    if (config.tcpPort > 0) {
        tcpBootstrap = new Bootstrap();
    }

    if (config.udpPort > 0) {
        udpBootstrap = new Bootstrap();
    }

    if (localBootstrap == null && tcpBootstrap == null && udpBootstrap == null) {
        throw new IllegalArgumentException(
                "You must define how you want to connect, either LOCAL channel name, TCP port, or UDP port");
    }

    if (config.localChannelName != null) {
        // no networked bootstraps. LOCAL connection only

        bootstraps.add(new BootstrapWrapper("LOCAL", config.localChannelName, -1, localBootstrap));

        localBootstrap.group(newEventLoop(LOCAL, 1, threadName + "-JVM-BOSS")).channel(LocalChannel.class)
                .remoteAddress(new LocalAddress(config.localChannelName))
                .handler(new RegistrationLocalHandlerClient(threadName, registrationWrapper));
    }

    EventLoopGroup workerEventLoop = null;
    if (tcpBootstrap != null || udpBootstrap != null) {
        workerEventLoop = newEventLoop(config.workerThreadPoolSize, threadName);
    }

    if (tcpBootstrap != null) {
        bootstraps.add(new BootstrapWrapper("TCP", config.host, config.tcpPort, tcpBootstrap));

        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            tcpBootstrap.channel(OioSocketChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            tcpBootstrap.channel(EpollSocketChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            tcpBootstrap.channel(KQueueSocketChannel.class);
        } else {
            tcpBootstrap.channel(NioSocketChannel.class);
        }

        tcpBootstrap.group(newEventLoop(1, threadName + "-TCP-BOSS"))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))
                .remoteAddress(config.host, config.tcpPort).handler(new RegistrationRemoteHandlerClientTCP(
                        threadName, registrationWrapper, workerEventLoop));

        // android screws up on this!!
        tcpBootstrap.option(ChannelOption.TCP_NODELAY, !OS.isAndroid()).option(ChannelOption.SO_KEEPALIVE,
                true);
    }

    if (udpBootstrap != null) {
        bootstraps.add(new BootstrapWrapper("UDP", config.host, config.udpPort, udpBootstrap));

        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            udpBootstrap.channel(OioDatagramChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            udpBootstrap.channel(EpollDatagramChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            udpBootstrap.channel(KQueueDatagramChannel.class);
        } else {
            udpBootstrap.channel(NioDatagramChannel.class);
        }

        udpBootstrap.group(newEventLoop(1, threadName + "-UDP-BOSS"))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                // Netty4 has a default of 2048 bytes as upper limit for datagram packets.
                .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(EndPoint.udpMaxSize))
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))
                .localAddress(new InetSocketAddress(0)) // bind to wildcard
                .remoteAddress(new InetSocketAddress(config.host, config.udpPort))
                .handler(new RegistrationRemoteHandlerClientUDP(threadName, registrationWrapper,
                        workerEventLoop));

        // Enable to READ and WRITE MULTICAST data (ie, 192.168.1.0)
        // in order to WRITE: write as normal, just make sure it ends in .255
        // in order to LISTEN:
        //    InetAddress group = InetAddress.getByName("203.0.113.0");
        //    NioDatagramChannel.joinGroup(group);
        // THEN once done
        //    NioDatagramChannel.leaveGroup(group), close the socket
        udpBootstrap.option(ChannelOption.SO_BROADCAST, false).option(ChannelOption.SO_SNDBUF, udpMaxSize);
    }
}