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:org.apache.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 w  w  . j a  va  2s  .  c o m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = this.serverBootstrap
            .group(this.eventLoopGroupBoss, this.eventLoopGroupSelector).channel(NioServerSocketChannel.class)
            .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();
    }

    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:org.apache.tinkerpop.gremlin.server.GremlinServer.java

License:Apache License

/**
 * Start Gremlin Server with {@link Settings} provided to the constructor.
 *///from w ww  . j  a  v a  2 s .  com
public synchronized CompletableFuture<ServerGremlinExecutor<EventLoopGroup>> start() throws Exception {
    if (serverStarted != null) {
        // server already started - don't get it rolling again
        return serverStarted;
    }

    serverStarted = new CompletableFuture<>();
    final CompletableFuture<ServerGremlinExecutor<EventLoopGroup>> serverReadyFuture = serverStarted;
    try {
        final ServerBootstrap b = new ServerBootstrap();

        // when high value is reached then the channel becomes non-writable and stays like that until the
        // low value is so that there is time to recover
        b.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, settings.writeBufferHighWaterMark);
        b.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, settings.writeBufferLowWaterMark);
        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        // fire off any lifecycle scripts that were provided by the user. hooks get initialized during
        // ServerGremlinExecutor initialization
        serverGremlinExecutor.getHooks().forEach(hook -> {
            logger.info("Executing start up {}", LifeCycleHook.class.getSimpleName());
            try {
                hook.onStartUp(new LifeCycleHook.Context(logger));
            } catch (UnsupportedOperationException uoe) {
                // if the user doesn't implement onStartUp the scriptengine will throw
                // this exception.  it can safely be ignored.
            }
        });

        final Channelizer channelizer = createChannelizer(settings);
        channelizer.init(serverGremlinExecutor);
        b.group(bossGroup, workerGroup).childHandler(channelizer);
        if (isEpollEnabled) {
            b.channel(EpollServerSocketChannel.class);
        } else {
            b.channel(NioServerSocketChannel.class);
        }

        // bind to host/port and wait for channel to be ready
        b.bind(settings.host, settings.port).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(final ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    ch = channelFuture.channel();

                    logger.info(
                            "Gremlin Server configured with worker thread pool of {}, gremlin pool of {} and boss thread pool of {}.",
                            settings.threadPoolWorker, settings.gremlinPool, settings.threadPoolBoss);
                    logger.info("Channel started at port {}.", settings.port);

                    serverReadyFuture.complete(serverGremlinExecutor);
                } else {
                    serverReadyFuture.completeExceptionally(new IOException(String.format(
                            "Could not bind to %s and %s - perhaps something else is bound to that address.",
                            settings.host, settings.port)));
                }
            }
        });
    } catch (Exception ex) {
        logger.error("Gremlin Server Error", ex);
        serverReadyFuture.completeExceptionally(ex);
    }

    return serverStarted;
}

From source file:org.atmosphere.nettosphere.Nettosphere.java

License:Apache License

private void configureBootstrap(ServerBootstrap bootstrap, Config config) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, config.socketNoTcpDelay());
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, config.socketKeepAlive());
}

From source file:org.ballerinalang.test.agent.server.WebServer.java

License:Open Source License

/**
 * Initializes the server, socket, and channel.
 *
 * @param loopGroup The event loop group.
 * @param serverChannelClass The socket channel class.
 * @throws InterruptedException on interruption.
 *///from   w w w  .  ja v  a2  s. c om
private void start(final EventLoopGroup loopGroup, final Class<? extends ServerChannel> serverChannelClass)
        throws InterruptedException {
    try {
        final InetSocketAddress inet = new InetSocketAddress(host, port);

        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        serverBootstrap.option(ChannelOption.SO_REUSEADDR, true);
        serverBootstrap.group(loopGroup).channel(serverChannelClass).childHandler(new WebServerInitializer());
        serverBootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
        serverBootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
        serverBootstrap.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);

        final Channel ch = serverBootstrap.bind(inet).sync().channel();
        ch.closeFuture().sync();
    } finally {
        loopGroup.shutdownGracefully().sync();
    }
}

From source file:org.cane.rpc.server.NettyRpcServer.java

License:Open Source License

@Override
public void start() {
    bossGroup = new NioEventLoopGroup();
    workGroup = new NioEventLoopGroup();
    try {/*from   ww w. ja va  2s .  c o  m*/
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline().addLast();
            }
        });
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        String[] hostAndPort = serverAddress.split(":");

        ChannelFuture future = serverBootstrap.bind(hostAndPort[0], Integer.parseInt(hostAndPort[1])).sync();

        if (serviceRegistry != null) {
            serviceRegistry.registerServer(serverAddress);
        }

        future.channel().closeFuture().sync();
    } catch (Exception e) {
        LOG.error("Init rpc server error!", e);
    }
}

From source file:org.conscrypt.testing.NettyServer.java

License:Apache License

public void start() {
    group = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(group);/*from  w  ww  . j av a 2  s  .c  om*/
    b.channel(NioServerSocketChannel.class);
    b.option(SO_BACKLOG, 128);
    b.childOption(SO_KEEPALIVE, true);
    b.childHandler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(final Channel ch) throws Exception {
            SslContext context = TestUtil.newNettyServerContext(cipher);
            SSLEngine sslEngine = context.newEngine(ch.alloc());
            ch.pipeline().addFirst(new SslHandler(sslEngine));
            ch.pipeline().addLast(new MessageDecoder());
        }
    });
    // Bind and start to accept incoming connections.
    ChannelFuture future = b.bind(port);
    try {
        future.await();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Interrupted waiting for bind");
    }
    if (!future.isSuccess()) {
        throw new RuntimeException("Failed to bind", future.cause());
    }
    channel = future.channel();
}

From source file:org.elasticsearch.hadoop.transport.netty4.Netty4Transport.java

License:Apache License

private void createServerBootstrap(String name, Settings settings) {
    if (logger.isDebugEnabled()) {
        logger.debug(//from   w w w.  j  ava 2s .c om
                "using profile[{}], worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], "
                        + "connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]",
                name, workerCount, settings.get("port"), settings.get("bind_host"),
                settings.get("publish_host"), compress, connectTimeout, connectionsPerNodeRecovery,
                connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing,
                receivePredictorMin, receivePredictorMax);
    }

    final ThreadFactory workerFactory = daemonThreadFactory(this.settings,
            HTTP_SERVER_WORKER_THREAD_NAME_PREFIX, name);

    final ServerBootstrap serverBootstrap = new ServerBootstrap();

    if (TCP_BLOCKING_SERVER.get(settings)) {
        serverBootstrap.group(new OioEventLoopGroup(workerCount, workerFactory));
        serverBootstrap.channel(OioServerSocketChannel.class);
    } else {
        serverBootstrap.group(new NioEventLoopGroup(workerCount, workerFactory));
        serverBootstrap.channel(NioServerSocketChannel.class);
    }

    serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("open_channels", Netty4Transport.this.serverOpenChannels);
            ch.pipeline().addLast("size", new Netty4SizeHeaderFrameDecoder());
            ch.pipeline().addLast("dispatcher", new Netty4MessageChannelHandler(Netty4Transport.this, name));
        }
    });

    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings));
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.getDefault(settings);
    if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.getDefault(settings);
    if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF,
                Math.toIntExact(tcpReceiveBufferSize.bytesAsInt()));
    }

    serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
    serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings);
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress);

    serverBootstrap.validate();

    serverBootstraps.put(name, serverBootstrap);
}

From source file:org.elasticsearch.transport.netty4.Netty4Transport.java

License:Apache License

private void createServerBootstrap(String name, Settings settings) {
    if (logger.isDebugEnabled()) {
        logger.debug(/*from  ww w .ja va2 s.  co m*/
                "using profile[{}], worker_count[{}], port[{}], bind_host[{}], publish_host[{}], compress[{}], "
                        + "connect_timeout[{}], connections_per_node[{}/{}/{}/{}/{}], receive_predictor[{}->{}]",
                name, workerCount, settings.get("port"), settings.get("bind_host"),
                settings.get("publish_host"), compress, connectTimeout, connectionsPerNodeRecovery,
                connectionsPerNodeBulk, connectionsPerNodeReg, connectionsPerNodeState, connectionsPerNodePing,
                receivePredictorMin, receivePredictorMax);
    }

    final ThreadFactory workerFactory = daemonThreadFactory(this.settings,
            TRANSPORT_SERVER_WORKER_THREAD_NAME_PREFIX, name);

    final ServerBootstrap serverBootstrap = new ServerBootstrap();

    if (TCP_BLOCKING_SERVER.get(settings)) {
        serverBootstrap.group(new OioEventLoopGroup(workerCount, workerFactory));
        serverBootstrap.channel(OioServerSocketChannel.class);
    } else {
        serverBootstrap.group(new NioEventLoopGroup(workerCount, workerFactory));
        serverBootstrap.channel(NioServerSocketChannel.class);
    }

    serverBootstrap.childHandler(getServerChannelInitializer(name, settings));

    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, TCP_NO_DELAY.get(settings));
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, TCP_KEEP_ALIVE.get(settings));

    final ByteSizeValue tcpSendBufferSize = TCP_SEND_BUFFER_SIZE.getDefault(settings);
    if (tcpSendBufferSize != null && tcpSendBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.bytes()));
    }

    final ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.getDefault(settings);
    if (tcpReceiveBufferSize != null && tcpReceiveBufferSize.bytes() > 0) {
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF,
                Math.toIntExact(tcpReceiveBufferSize.bytesAsInt()));
    }

    serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);
    serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator);

    final boolean reuseAddress = TCP_REUSE_ADDRESS.get(settings);
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, reuseAddress);

    serverBootstrap.validate();

    serverBootstraps.put(name, serverBootstrap);
}

From source file:org.gameoss.gridcast.p2p.node.NodeServer.java

License:Apache License

public void initialize(final String host, final int port, final EventLoopGroup bossGroup,
        final EventLoopGroup workerGroup, final MessageRegistry messageRegistry,
        final ChannelInboundHandlerAdapter channelListener) {
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(bossGroup, workerGroup);//from w  w w  .  java  2s.com
    boot.channel(NioServerSocketChannel.class);
    boot.option(ChannelOption.SO_BACKLOG, 32);
    boot.childOption(ChannelOption.SO_KEEPALIVE, true);
    boot.childOption(ChannelOption.TCP_NODELAY, true);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();

            // encoders
            p.addLast(new LengthFieldPrepender(4));
            p.addLast(new ProtostuffEncoder(messageRegistry));

            // decoders
            p.addLast(new LengthFieldBasedFrameDecoder(0x100000, 0, 4, 0, 4));
            p.addLast(new ProtostuffDecoder(messageRegistry));
            p.addLast(channelListener);
        }
    });

    // start accepting connection
    try {
        if (host == null) {
            acceptChannel = boot.bind(port).sync().channel();
        } else {
            acceptChannel = boot.bind(host, port).sync().channel();
        }
    } catch (InterruptedException e) {
        logger.error("Binding to port {} failed", port, e);
    }

}

From source file:org.hongxi.whatsmars.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. j a  va 2 s  . c om
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = this.serverBootstrap
            .group(this.eventLoopGroupBoss, this.eventLoopGroupSelector)
            .channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
            .childOption(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, HANDSHAKE_HANDLER_NAME,
                                    new HandshakeHandler(TlsSystemConfig.tlsMode))
                            .addLast(defaultEventExecutorGroup, new NettyEncoder(), new NettyDecoder(),
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),
                                    new NettyConnectManageHandler(), 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.nettyEventExecutor.start();
    }

    this.timer.scheduleAtFixedRate(new TimerTask() {

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