Example usage for io.netty.bootstrap ServerBootstrap childOption

List of usage examples for io.netty.bootstrap ServerBootstrap childOption

Introduction

In this page you can find the example usage for io.netty.bootstrap ServerBootstrap childOption.

Prototype

public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value) 

Source Link

Document

Allow to specify a ChannelOption which is used for the Channel instances once they get created (after the acceptor accepted the Channel ).

Usage

From source file:NettyHttpListner.java

License:Apache License

public void start() {

    System.out.println("Starting the server...");
    System.out.println("Starting Inbound Http Listner on Port " + this.port);

    // Configure SSL.
    SslContext sslCtx = null;/*from  w  ww . ja va 2 s. c  om*/
    if (SSL) {
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (CertificateException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SSLException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    commonEventLoopGroup = new NioEventLoopGroup(bossGroupSize);
    //        bossGroup = new NioEventLoopGroup(bossGroupSize);
    //        workerGroup = new NioEventLoopGroup(workerGroupSize);

    try {
        ServerBootstrap b = new ServerBootstrap();

        //            b.commonEventLoopGroup(bossGroup, workerGroup)
        b.group(commonEventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(
                        new NettyHttpTransportHandlerInitializer(HOST, HOST_PORT, maxConnectionsQueued, sslCtx))
                .childOption(ChannelOption.AUTO_READ, false);

        b.option(ChannelOption.TCP_NODELAY, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);

        b.option(ChannelOption.SO_BACKLOG, maxConnectionsQueued);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

        b.option(ChannelOption.SO_SNDBUF, 1048576);
        b.option(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_SNDBUF, 1048576);

        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        Channel ch = null;
        try {
            ch = b.bind(port).sync().channel();
            ch.closeFuture().sync();
            System.out.println("Inbound Listner Started");
        } catch (InterruptedException e) {
            System.out.println("Exception caught");
        }
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:alluxio.worker.netty.NettyDataServer.java

License:Apache License

private ServerBootstrap createBootstrap() {
    final ServerBootstrap boot = createBootstrapOfType(
            Configuration.getEnum(PropertyKey.WORKER_NETWORK_NETTY_CHANNEL, ChannelType.class));

    // use pooled buffers
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // set write buffer
    // this is the default, but its recommended to set it in case of change in future netty.
    boot.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK,
            (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_WATERMARK_HIGH));
    boot.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK,
            (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_WATERMARK_LOW));

    // more buffer settings on Netty socket option, one can tune them by specifying
    // properties, e.g.:
    // alluxio.worker.network.netty.backlog=50
    // alluxio.worker.network.netty.buffer.send=64KB
    // alluxio.worker.network.netty.buffer.receive=64KB
    if (Configuration.containsKey(PropertyKey.WORKER_NETWORK_NETTY_BACKLOG)) {
        boot.option(ChannelOption.SO_BACKLOG, Configuration.getInt(PropertyKey.WORKER_NETWORK_NETTY_BACKLOG));
    }/*from  w  ww.j  av a 2  s . c  o  m*/
    if (Configuration.containsKey(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_SEND)) {
        boot.option(ChannelOption.SO_SNDBUF,
                (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_SEND));
    }
    if (Configuration.containsKey(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_RECEIVE)) {
        boot.option(ChannelOption.SO_RCVBUF,
                (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_RECEIVE));
    }
    return boot;
}

From source file:com.addthis.hydra.query.web.QueryServer.java

License:Apache License

public void run() throws Exception {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    executorGroup = new DefaultEventExecutorGroup(AggregateConfig.FRAME_READER_THREADS,
            new ThreadFactoryBuilder().setDaemon(true).setNameFormat("frame-reader-%d").build());
    for (EventExecutor executor : executorGroup) {
        executor.execute(new NextQueryTask(queryQueue, executor));
    }//  ww  w  .j a v a  2s. c  o m
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.childOption(ChannelOption.MESSAGE_SIZE_ESTIMATOR, new DefaultMessageSizeEstimator(200));
    b.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 100000000);
    b.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 50000000);
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(queryServerInitializer);
    b.bind(webPort).sync();
}

From source file:com.alibaba.dubbo.qos.server.Server.java

License:Apache License

/**
 * start server, bind port/*w w  w.  ja va 2s. com*/
 */
public void start() throws Throwable {
    if (!hasStarted.compareAndSet(false, true)) {
        return;
    }
    boss = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-boss", true));
    worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true));
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(boss, worker);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    serverBootstrap.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new QosProcessHandler(welcome, acceptForeignIp));
        }
    });
    try {
        serverBootstrap.bind(port).sync();
        logger.info("qos-server bind localhost:" + port);
    } catch (Throwable throwable) {
        logger.error("qos-server can not bind localhost:" + port, throwable);
        throw throwable;
    }
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyRemotingServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/*from  w  ww .  ja v  a 2  s . c o m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker);
    if (isLinux) {
        childHandler.channel(EpollServerSocketChannel.class);
    } else {
        childHandler.channel(NioServerSocketChannel.class);
    }
    if (isLinux) {
        childHandler.option(EpollChannelOption.SO_REUSEPORT, true);
    }
    //
    childHandler.option(ChannelOption.SO_BACKLOG, 1024)
            //
            .option(ChannelOption.SO_REUSEADDR, true)
            //
            .option(ChannelOption.SO_KEEPALIVE, false)
            //
            .childOption(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
            //
            .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
            //
            .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(
                            //
                            defaultEventExecutorGroup, //
                            new NettyEncoder(), //
                            new NettyDecoder(), //
                            new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                            new NettyConnetManageHandler(), //
                            new NettyServerHandler());
                }
            });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        // ????
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}

From source file:com.ancun.netty.httpserver.HttpServer.java

License:Apache License

private void setBootstrapOptions(ServerBootstrap bootstrap) {
    bootstrap.option(ChannelOption.SO_KEEPALIVE, useKeepAlive());
    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
    bootstrap.option(ChannelOption.TCP_NODELAY, useTcpNoDelay());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, serverSettings.isKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, shouldReuseAddress());
    bootstrap.option(ChannelOption.SO_LINGER, getSoLinger());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeoutMillis());
    bootstrap.option(ChannelOption.SO_RCVBUF, getReceiveBufferSize());
    bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);

    bootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
    bootstrap.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, getReceiveBufferSize());
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, shouldReuseAddress());
}

From source file:com.caricah.iotracah.server.netty.ServerImpl.java

License:Apache License

/**
 * The @link configure method is responsible for starting the implementation server processes.
 * The implementation should return once the server has started this allows
 * the launcher to maintain the life of the application.
 *
 * @throws UnRetriableException/*from  w w w .  ja v a  2  s . c  o  m*/
 */
public void initiate() throws UnRetriableException {

    log.info(" configure : initiating the netty server.");

    try {

        int countOfAvailableProcessors = Runtime.getRuntime().availableProcessors() + 1;

        if (Epoll.isAvailable()) {
            bossEventLoopGroup = new EpollEventLoopGroup(2, getExecutorService());
            workerEventLoopGroup = new EpollEventLoopGroup(countOfAvailableProcessors, getExecutorService());

        } else {
            bossEventLoopGroup = new NioEventLoopGroup(2, getExecutorService());
            workerEventLoopGroup = new NioEventLoopGroup(countOfAvailableProcessors, getExecutorService());
        }

        //Initialize listener for TCP
        ServerBootstrap tcpBootstrap = new ServerBootstrap();
        tcpBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        tcpBootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
        tcpBootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

        tcpBootstrap = tcpBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);

        if (Epoll.isAvailable()) {
            tcpBootstrap = tcpBootstrap.channel(EpollServerSocketChannel.class);
        } else {
            tcpBootstrap = tcpBootstrap.channel(NioServerSocketChannel.class);
        }

        tcpBootstrap = tcpBootstrap.handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(getServerInitializer(this, getConnectionTimeout()));

        ChannelFuture tcpChannelFuture = tcpBootstrap.bind(getTcpPort()).sync();
        tcpChannel = tcpChannelFuture.channel();

        if (isSslEnabled()) {
            //Initialize listener for SSL
            ServerBootstrap sslBootstrap = new ServerBootstrap();
            sslBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            sslBootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
            sslBootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

            sslBootstrap = sslBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);

            if (Epoll.isAvailable()) {
                sslBootstrap = sslBootstrap.channel(EpollServerSocketChannel.class);
            } else {
                sslBootstrap = sslBootstrap.channel(NioServerSocketChannel.class);
            }

            sslBootstrap = sslBootstrap.handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(getServerInitializer(this, getConnectionTimeout(), getSslHandler()));

            ChannelFuture sslChannelFuture = sslBootstrap.bind(getSslPort()).sync();
            sslChannel = sslChannelFuture.channel();
        }

    } catch (InterruptedException e) {

        log.error(" configure : Initialization issues ", e);

        throw new UnRetriableException(e);

    }

}

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 .  j  ava  2  s .  c o m*/
    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.dinstone.jrpc.transport.netty4.NettyAcceptance.java

License:Apache License

@Override
public Acceptance bind() {
    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("N4A-Boss"));
    workGroup = new NioEventLoopGroup(transportConfig.getNioProcessorCount(),
            new DefaultThreadFactory("N4A-Work"));

    ServerBootstrap boot = new ServerBootstrap().group(bossGroup, workGroup);
    boot.channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override/*from   w  w  w.j  a  v  a2  s  . c  o m*/
        public void initChannel(SocketChannel ch) throws Exception {
            TransportProtocolDecoder decoder = new TransportProtocolDecoder();
            decoder.setMaxObjectSize(transportConfig.getMaxSize());
            TransportProtocolEncoder encoder = new TransportProtocolEncoder();
            encoder.setMaxObjectSize(transportConfig.getMaxSize());
            ch.pipeline().addLast("TransportProtocolDecoder", decoder);
            ch.pipeline().addLast("TransportProtocolEncoder", encoder);

            int intervalSeconds = transportConfig.getHeartbeatIntervalSeconds();
            ch.pipeline().addLast("IdleStateHandler", new IdleStateHandler(intervalSeconds * 2, 0, 0));
            ch.pipeline().addLast("NettyServerHandler", new NettyServerHandler());
        }
    });
    boot.option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_BACKLOG, 128);
    boot.childOption(ChannelOption.SO_RCVBUF, 16 * 1024).childOption(ChannelOption.SO_SNDBUF, 16 * 1024)
            .childOption(ChannelOption.TCP_NODELAY, true);

    try {
        boot.bind(serviceAddress).sync();

        int processorCount = transportConfig.getBusinessProcessorCount();
        if (processorCount > 0) {
            NamedThreadFactory threadFactory = new NamedThreadFactory("N4A-BusinessProcessor");
            executorService = Executors.newFixedThreadPool(processorCount, threadFactory);
        }
    } catch (Exception e) {
        throw new RuntimeException("can't bind service on " + serviceAddress, e);
    }
    LOG.info("netty acceptance bind on {}", serviceAddress);

    return this;
}

From source file:com.dinstone.jrpc.transport.netty5.NettyAcceptance.java

License:Apache License

@Override
public Acceptance bind() {
    bossGroup = new NioEventLoopGroup(1, new DefaultExecutorServiceFactory("N5A-Boss"));
    workGroup = new NioEventLoopGroup(transportConfig.getNioProcessorCount(),
            new DefaultExecutorServiceFactory("N5A-Work"));

    ServerBootstrap boot = new ServerBootstrap();
    boot.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override//from w ww  .j a  v a2  s  .  c om
                public void initChannel(SocketChannel ch) throws Exception {
                    TransportProtocolDecoder decoder = new TransportProtocolDecoder();
                    decoder.setMaxObjectSize(transportConfig.getMaxSize());
                    TransportProtocolEncoder encoder = new TransportProtocolEncoder();
                    encoder.setMaxObjectSize(transportConfig.getMaxSize());
                    ch.pipeline().addLast("TransportProtocolDecoder", decoder);
                    ch.pipeline().addLast("TransportProtocolEncoder", encoder);

                    int intervalSeconds = transportConfig.getHeartbeatIntervalSeconds();
                    ch.pipeline().addLast("IdleStateHandler", new IdleStateHandler(intervalSeconds * 2, 0, 0));
                    ch.pipeline().addLast("NettyServerHandler", new NettyServerHandler());
                }
            });
    boot.option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_BACKLOG, 128);
    boot.childOption(ChannelOption.SO_RCVBUF, 16 * 1024).childOption(ChannelOption.SO_SNDBUF, 16 * 1024)
            .childOption(ChannelOption.TCP_NODELAY, true);

    try {
        boot.bind(serviceAddress).sync();

        int processorCount = transportConfig.getBusinessProcessorCount();
        if (processorCount > 0) {
            NamedThreadFactory threadFactory = new NamedThreadFactory("N5A-BusinssProcessor");
            executorService = Executors.newFixedThreadPool(processorCount, threadFactory);
        }
    } catch (Exception e) {
        throw new RuntimeException("can't bind service on " + serviceAddress, e);
    }
    LOG.info("netty5 acceptance bind on {}", serviceAddress);

    return this;
}