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.hornetq.tests.integration.transports.netty.NettyConnectorWithHTTPUpgradeTest.java

License:Apache License

private void startWebServer(int port) throws InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*www .  j  a  v a2 s. com*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    // create a HTTP server
                    ChannelPipeline p = ch.pipeline();
                    p.addLast("decoder", new HttpRequestDecoder());
                    p.addLast("encoder", new HttpResponseEncoder());
                    p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() {
                        // handle HTTP GET + Upgrade with a handshake specific to HornetQ remoting.
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (msg instanceof HttpRequest) {
                                HttpRequest request = (HttpRequest) msg;

                                for (Map.Entry<String, String> entry : request.headers()) {
                                    System.out.println(entry);
                                }
                                String upgrade = request.headers().get(UPGRADE);
                                String secretKey = request.headers().get(SEC_HORNETQ_REMOTING_KEY);

                                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                                        SWITCHING_PROTOCOLS);
                                response.headers().set(UPGRADE, upgrade);
                                response.headers().set(SEC_HORNETQ_REMOTING_ACCEPT,
                                        createExpectedResponse(MAGIC_NUMBER, secretKey));
                                ctx.writeAndFlush(response);

                                // when the handshake is successful, the HTTP handlers are removed
                                ctx.pipeline().remove("decoder");
                                ctx.pipeline().remove("encoder");
                                ctx.pipeline().remove(this);

                                System.out.println("HTTP handshake sent, transferring channel");
                                // transfer the control of the channel to the Netty Acceptor
                                NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService()
                                        .getAcceptor(acceptorName);
                                acceptor.transfer(ctx.channel());
                                // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones.
                            }
                        }
                    });
                }

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                    ctx.flush();
                }
            });
    b.bind(port).sync();
}

From source file:org.jooby.internal.netty.NettyServer.java

License:Apache License

private Channel bootstrap(final EventExecutorGroup executor, final SslContext sslCtx, final int port)
        throws InterruptedException {
    ServerBootstrap bootstrap = new ServerBootstrap();

    boolean epoll = bossLoop instanceof EpollEventLoopGroup;
    bootstrap.group(bossLoop, workerLoop)
            .channel(epoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .handler(new LoggingHandler(Server.class, LogLevel.DEBUG))
            .childHandler(new NettyPipeline(executor, dispatcher, conf, sslCtx));

    configure(conf.getConfig("netty.options"), "netty.options",
            (option, value) -> bootstrap.option(option, value));

    configure(conf.getConfig("netty.worker.options"), "netty.worker.options",
            (option, value) -> bootstrap.childOption(option, value));

    return bootstrap.bind(host(conf.getString("application.host")), port).sync().channel();
}

From source file:org.jupiter.transport.netty.NettyTcpAcceptor.java

License:Apache License

@Override
protected void setOptions() {
    super.setOptions();

    ServerBootstrap boot = bootstrap();

    // parent options
    NettyConfig.NettyTcpConfigGroup.ParentConfig parent = configGroup.parent();
    boot.option(ChannelOption.SO_BACKLOG, parent.getBacklog());
    boot.option(ChannelOption.SO_REUSEADDR, parent.isReuseAddress());
    if (parent.getRcvBuf() > 0) {
        boot.option(ChannelOption.SO_RCVBUF, parent.getRcvBuf());
    }/*from w ww . jav a 2s  .  c om*/

    // child options
    NettyConfig.NettyTcpConfigGroup.ChildConfig child = configGroup.child();
    boot.childOption(ChannelOption.SO_REUSEADDR, child.isReuseAddress())
            .childOption(ChannelOption.SO_KEEPALIVE, child.isKeepAlive())
            .childOption(ChannelOption.TCP_NODELAY, child.isTcpNoDelay())
            .childOption(ChannelOption.ALLOW_HALF_CLOSURE, child.isAllowHalfClosure());
    if (child.getRcvBuf() > 0) {
        boot.childOption(ChannelOption.SO_RCVBUF, child.getRcvBuf());
    }
    if (child.getSndBuf() > 0) {
        boot.childOption(ChannelOption.SO_SNDBUF, child.getSndBuf());
    }
    if (child.getLinger() > 0) {
        boot.childOption(ChannelOption.SO_LINGER, child.getLinger());
    }
    if (child.getIpTos() > 0) {
        boot.childOption(ChannelOption.IP_TOS, child.getIpTos());
    }
    int bufLowWaterMark = child.getWriteBufferLowWaterMark();
    int bufHighWaterMark = child.getWriteBufferHighWaterMark();
    if (bufLowWaterMark >= 0 && bufHighWaterMark > 0) {
        WriteBufferWaterMark waterMark = new WriteBufferWaterMark(bufLowWaterMark, bufHighWaterMark);
        boot.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
    }
}

From source file:org.jupiter.transport.netty.NettyUdtAcceptor.java

License:Apache License

@Override
protected void setOptions() {
    super.setOptions();

    ServerBootstrap boot = bootstrap();

    // parent options
    NettyUdtConfigGroup.ParentConfig parent = configGroup.parent();
    boot.option(ChannelOption.SO_BACKLOG, parent.getBacklog());

    // child options
    NettyUdtConfigGroup.ChildConfig child = configGroup.child();
    boot.childOption(ChannelOption.SO_REUSEADDR, child.isReuseAddress());
    if (child.getRcvBuf() > 0) {
        boot.childOption(ChannelOption.SO_RCVBUF, child.getRcvBuf());
    }/*  ww  w .  j  a va  2  s  . c  o  m*/
    if (child.getSndBuf() > 0) {
        boot.childOption(ChannelOption.SO_SNDBUF, child.getSndBuf());
    }
    if (child.getLinger() > 0) {
        boot.childOption(ChannelOption.SO_LINGER, child.getLinger());
    }
    int bufLowWaterMark = child.getWriteBufferLowWaterMark();
    int bufHighWaterMark = child.getWriteBufferHighWaterMark();
    if (bufLowWaterMark >= 0 && bufHighWaterMark > 0) {
        WriteBufferWaterMark waterMark = new WriteBufferWaterMark(bufLowWaterMark, bufHighWaterMark);
        boot.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, waterMark);
    }
}

From source file:org.lightmare.remote.rpc.RpcListener.java

License:Open Source License

/**
 * Starts RPC server/*from  www .j  a  v  a 2 s .  c o m*/
 * 
 */
public static void startServer(Configuration config) {

    setNettyPools(config);

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializerImpl());

        bootstrap.option(ChannelOption.SO_BACKLOG, 500);
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
        bootstrap.childOption(ChannelOption.SO_TIMEOUT, config.getIntValue(ConfigKeys.CONNECTION_TIMEOUT.key));

        InetSocketAddress address = new InetSocketAddress(
                Inet4Address.getByName(config.getStringValue("listening_ip")),
                config.getIntValue("listening_port"));
        ChannelFuture future = bootstrap.bind(address).sync();
        LOG.info(future);
    } catch (UnknownHostException ex) {
        LOG.error(ex.getMessage(), ex);
    } catch (InterruptedException ex) {
        LOG.error(ex.getMessage(), ex);
    }
}

From source file:org.marketcetera.util.rpc.RpcServer.java

@Override
@PostConstruct/* w  ww .j a  v a2 s .c om*/
public synchronized void start() {
    Validate.notNull(hostname);
    Validate.isTrue(port > 0 && port < 65536);
    Validate.notNull(sessionManager);
    Validate.notNull(authenticator);
    Validate.isTrue(threadPoolCore > 0);
    Validate.isTrue(threadPoolMax > 0);
    Validate.isTrue(threadPoolMax >= threadPoolCore);
    Validate.isTrue(sendBufferSize > 0);
    Validate.isTrue(receiveBufferSize > 0);
    Validate.notEmpty(serviceSpecs);
    Messages.SERVER_STARTING.info(this, hostname, port);
    if (isRunning()) {
        stop();
    }
    try {
        reportContext = JAXBContext.newInstance(
                contextClassProvider == null ? new Class<?>[0] : contextClassProvider.getContextClasses());
        marshaller = reportContext.createMarshaller();
        unmarshaller = reportContext.createUnmarshaller();
    } catch (JAXBException e) {
        SLF4JLoggerProxy.error(this, e);
        throw new RuntimeException(e);
    }
    PeerInfo serverInfo = new PeerInfo(getRpcHostname(), getRpcPort());
    executor = new ThreadPoolCallExecutor(threadPoolCore, threadPoolMax);
    DuplexTcpServerPipelineFactory serverFactory = new DuplexTcpServerPipelineFactory(serverInfo);
    serverFactory.setRpcServerCallExecutor(executor);
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(
            new NioEventLoopGroup(0, new RenamingThreadFactoryProxy("boss", Executors.defaultThreadFactory())),
            new NioEventLoopGroup(0,
                    new RenamingThreadFactoryProxy("worker", Executors.defaultThreadFactory())));
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(serverFactory);
    bootstrap.localAddress(serverInfo.getPort());
    bootstrap.option(ChannelOption.SO_SNDBUF, sendBufferSize);
    bootstrap.option(ChannelOption.SO_RCVBUF, receiveBufferSize);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, receiveBufferSize);
    bootstrap.childOption(ChannelOption.SO_SNDBUF, sendBufferSize);
    bootstrap.option(ChannelOption.TCP_NODELAY, noDelay);
    for (RpcServiceSpec<SessionClazz> serviceSpec : serviceSpecs) {
        serviceSpec.setRpcServerServices(this);
        BlockingService activeService = serviceSpec.generateService();
        serverFactory.getRpcServiceRegistry().registerService(activeService);
        Messages.SERVICE_STARTING.info(this, serviceSpec.getDescription());
    }
    channelToken = bootstrap.bind();
    while (!channelToken.isDone()) {
        try {
            Thread.sleep(250);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    // TODO throw exception?
    running.set(channelToken.isSuccess());
    //RpcClientConnectionRegistry clientRegistry = new RpcClientConnectionRegistry();
    //serverFactory.registerConnectionEventListener(clientRegistry);
}

From source file:org.mobicents.protocols.sctp.netty.NettyServerImpl.java

License:Open Source License

private void applySctpOptions(ServerBootstrap b) {
    b.childOption(SctpChannelOption.SCTP_NODELAY, this.management.getOptionSctpNodelay());
    b.childOption(SctpChannelOption.SCTP_DISABLE_FRAGMENTS, this.management.getOptionSctpDisableFragments());
    b.childOption(SctpChannelOption.SCTP_FRAGMENT_INTERLEAVE,
            this.management.getOptionSctpFragmentInterleave());
    b.childOption(SctpChannelOption.SCTP_INIT_MAXSTREAMS, this.management.getOptionSctpInitMaxstreams());
    b.childOption(SctpChannelOption.SO_SNDBUF, this.management.getOptionSoSndbuf());
    b.childOption(SctpChannelOption.SO_RCVBUF, this.management.getOptionSoRcvbuf());
    b.childOption(SctpChannelOption.SO_LINGER, this.management.getOptionSoLinger());
}

From source file:org.msgpack.rpc.loop.netty.NettyTcpServerTransport.java

License:Apache License

NettyTcpServerTransport(TcpServerConfig config, Server server, NettyEventLoop loop,
        Class<? extends RpcMessageHandler> rpcHandlerClass) {
    if (server == null) {
        throw new IllegalArgumentException("Server must not be null");
    }/*from  w  ww  .  ja  v  a  2 s  .  c o m*/

    Address address = config.getListenAddress();

    try {
        RpcMessageHandler handler = rpcHandlerClass.getConstructor(Server.class).newInstance(server);
        handler.useThread(true);

        ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class);

        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast("msgpack-decode-stream", new MessagePackStreamDecoder(loop.getMessagePack()));
                p.addLast("msgpack-encode", new MessagePackEncoder(loop.getMessagePack()));
                p.addLast("message", new MessageHandler(handler));
            }

        });
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.localAddress(address.getSocketAddress());
        future = bootstrap.bind();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    //      RpcMessageHandler handler = new RpcMessageHandlerEx(server);

}

From source file:org.onlab.netty.NettyMessaging.java

License:Apache License

private void startAcceptingConnections() throws InterruptedException {
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
    b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    b.option(ChannelOption.SO_RCVBUF, 1048576);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.group(serverGroup, clientGroup);/*from ww w.  java  2s . c  o  m*/
    b.channel(serverChannelClass);
    if (enableNettyTLS) {
        b.childHandler(new SSLServerCommunicationChannelInitializer());
    } else {
        b.childHandler(new OnosCommunicationChannelInitializer());
    }
    b.option(ChannelOption.SO_BACKLOG, 128);
    b.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    b.bind(localEp.port()).sync().addListener(future -> {
        if (future.isSuccess()) {
            log.info("{} accepting incoming connections on port {}", localEp.host(), localEp.port());
        } else {
            log.warn("{} failed to bind to port {}", localEp.host(), localEp.port(), future.cause());
        }
    });
}

From source file:org.onosproject.openflow.controller.impl.Controller.java

License:Apache License

/**
 * Tell controller that we're ready to accept switches loop.
 *//* w  w w. j  av a 2  s . c  o m*/
public void run() {

    try {
        final ServerBootstrap bootstrap = createServerBootStrap();
        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        bootstrap.childOption(ChannelOption.SO_SNDBUF, Controller.SEND_BUFFER_SIZE);
        //            bootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
        //                                  new WriteBufferWaterMark(8 * 1024, 32 * 1024));

        bootstrap.childHandler(new OFChannelInitializer(this, null, sslContext));

        openFlowPorts.forEach(port -> {
            // TODO revisit if this is best way to listen to multiple ports
            cg.add(bootstrap.bind(port).syncUninterruptibly().channel());
            log.info("Listening for switch connections on {}", port);
        });

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}