Example usage for io.netty.bootstrap ServerBootstrap childHandler

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

Introduction

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

Prototype

ChannelHandler childHandler

To view the source code for io.netty.bootstrap ServerBootstrap childHandler.

Click Source Link

Usage

From source file:org.apache.dubbo.qos.server.Server.java

License:Apache License

/**
 * start server, bind port//from   w ww  . j  ava  2s. c  o  m
 */
public void start() throws Throwable {
    if (!started.compareAndSet(false, true)) {
        return;
    }
    boss = new NioEventLoopGroup(1, 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:org.apache.hadoop.hbase.ipc.NettyRpcServer.java

License:Apache License

public NettyRpcServer(final Server server, final String name, final List<BlockingServiceAndInterface> services,
        final InetSocketAddress bindAddress, Configuration conf, RpcScheduler scheduler) throws IOException {
    super(server, name, services, bindAddress, conf, scheduler);
    this.bindAddress = bindAddress;
    boolean useEpoll = useEpoll(conf);
    int workerCount = conf.getInt("hbase.netty.rpc.server.worker.count",
            Runtime.getRuntime().availableProcessors() / 4);
    EventLoopGroup bossGroup = null;/*from w ww .  j a  v a 2s.c  o  m*/
    EventLoopGroup workerGroup = null;
    if (useEpoll) {
        bossGroup = new EpollEventLoopGroup(1);
        workerGroup = new EpollEventLoopGroup(workerCount);
    } else {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup(workerCount);
    }
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup);
    if (useEpoll) {
        bootstrap.channel(EpollServerSocketChannel.class);
    } else {
        bootstrap.channel(NioServerSocketChannel.class);
    }
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, tcpKeepAlive);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.childHandler(new Initializer(maxRequestSize));

    try {
        serverChannel = bootstrap.bind(this.bindAddress).sync().channel();
        LOG.info("NettyRpcServer bind to address=" + serverChannel.localAddress()
                + ", hbase.netty.rpc.server.worker.count=" + workerCount + ", useEpoll=" + useEpoll);
        allChannels.add(serverChannel);
    } catch (InterruptedException e) {
        throw new InterruptedIOException(e.getMessage());
    }
    initReconfigurable(conf);
    this.scheduler.init(new RpcSchedulerContext(this));
}

From source file:org.apache.pulsar.proxy.server.ProxyService.java

License:Apache License

public void start() throws Exception {
    if (!isBlank(proxyConfig.getZookeeperServers()) && !isBlank(proxyConfig.getConfigurationStoreServers())) {
        discoveryProvider = new BrokerDiscoveryProvider(this.proxyConfig, getZooKeeperClientFactory());
        this.configurationCacheService = new ConfigurationCacheService(discoveryProvider.globalZkCache);
        authorizationService = new AuthorizationService(PulsarConfigurationLoader.convertFrom(proxyConfig),
                configurationCacheService);
    }/*  www  .j a  va  2 s . c o m*/

    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));

    bootstrap.channel(EventLoopUtil.getServerSocketChannelClass(workerGroup));
    EventLoopUtil.enableTriggeredMode(bootstrap);

    bootstrap.childHandler(new ServiceChannelInitializer(this, proxyConfig, false));
    // Bind and start to accept incoming connections.
    if (proxyConfig.getServicePort().isPresent()) {
        try {
            bootstrap.bind(proxyConfig.getServicePort().get()).sync();
            LOG.info("Started Pulsar Proxy at {}", serviceUrl);
        } catch (Exception e) {
            throw new IOException("Failed to bind Pulsar Proxy on port " + proxyConfig.getServicePort().get(),
                    e);
        }
    }
    LOG.info("Started Pulsar Proxy at {}", serviceUrl);

    if (proxyConfig.getServicePortTls().isPresent()) {
        ServerBootstrap tlsBootstrap = bootstrap.clone();
        tlsBootstrap.childHandler(new ServiceChannelInitializer(this, proxyConfig, true));
        tlsBootstrap.bind(proxyConfig.getServicePortTls().get()).sync();
        LOG.info("Started Pulsar TLS Proxy on port {}", proxyConfig.getServicePortTls().get());
    }
}

From source file:org.apache.qpid.jms.transports.netty.NettyServer.java

License:Apache License

public void start() throws Exception {

    if (started.compareAndSet(false, true)) {

        // Configure the server.
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();

        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workerGroup);
        server.channel(NioServerSocketChannel.class);
        server.option(ChannelOption.SO_BACKLOG, 100);
        server.handler(new LoggingHandler(LogLevel.INFO));
        server.childHandler(new ChannelInitializer<Channel>() {

            @Override//  www  .j  av  a2 s. c o  m
            public void initChannel(Channel ch) throws Exception {
                if (options instanceof TransportSslOptions) {
                    TransportSslOptions sslOptions = (TransportSslOptions) options;
                    SSLContext context = TransportSupport.createSslContext(sslOptions);
                    SSLEngine engine = TransportSupport.createSslEngine(context, sslOptions);
                    engine.setUseClientMode(false);
                    engine.setNeedClientAuth(needClientAuth);
                    sslHandler = new SslHandler(engine);
                    ch.pipeline().addLast(sslHandler);
                }

                if (webSocketServer) {
                    ch.pipeline().addLast(new HttpServerCodec());
                    ch.pipeline().addLast(new HttpObjectAggregator(65536));
                    ch.pipeline().addLast(new WebSocketServerProtocolHandler(getWebSocketPath(), "amqp", true));
                }

                ch.pipeline().addLast(new NettyServerOutboundHandler());
                ch.pipeline().addLast(new NettyServerInboundHandler());
                ch.pipeline().addLast(getServerHandler());
            }
        });

        // Start the server.
        serverChannel = server.bind(getServerPort()).sync().channel();
    }
}

From source file:org.apache.tajo.pullserver.TajoPullServerService.java

License:Apache License

@Override
public void serviceInit(Configuration conf) throws Exception {
    if (!(conf instanceof TajoConf)) {
        throw new IllegalArgumentException("Configuration must be a TajoConf instance");
    }/* ww  w  . j  av a2s  .  c om*/

    ServerBootstrap bootstrap = selector.clone();
    TajoConf tajoConf = (TajoConf) conf;
    try {
        channelInitializer = new HttpChannelInitializer(tajoConf);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    bootstrap.childHandler(channelInitializer).channel(NioServerSocketChannel.class);

    port = conf.getInt(ConfVars.PULLSERVER_PORT.varname, ConfVars.PULLSERVER_PORT.defaultIntVal);
    ChannelFuture future = bootstrap.bind(new InetSocketAddress(port))
            .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE).syncUninterruptibly();

    accepted.add(future.channel());
    port = ((InetSocketAddress) future.channel().localAddress()).getPort();
    conf.set(ConfVars.PULLSERVER_PORT.varname, Integer.toString(port));
    LOG.info(getName() + " listening on port " + port);

    sslFileBufferSize = conf.getInt(SUFFLE_SSL_FILE_BUFFER_SIZE_KEY, DEFAULT_SUFFLE_SSL_FILE_BUFFER_SIZE);

    if (STANDALONE) {
        File pullServerPortFile = getPullServerPortFile();
        if (pullServerPortFile.exists()) {
            pullServerPortFile.delete();
        }
        pullServerPortFile.getParentFile().mkdirs();
        LOG.info("Write PullServerPort to " + pullServerPortFile);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(pullServerPortFile);
            out.write(("" + port).getBytes());
        } catch (Exception e) {
            LOG.fatal("PullServer exists cause can't write PullServer port to " + pullServerPortFile + ", "
                    + e.getMessage(), e);
            System.exit(-1);
        } finally {
            IOUtils.closeStream(out);
        }
    }
    super.serviceInit(conf);
    LOG.info("TajoPullServerService started: port=" + port);
}

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

License:Apache License

private ServerBootstrap buildBootstrap(Config config) {
    final ServerBootstrap bootstrap = new ServerBootstrap();
    parentGroup = config.epoll() ? new EpollEventLoopGroup() : new NioEventLoopGroup();
    childGroup = config.epoll() ? new EpollEventLoopGroup() : new NioEventLoopGroup();
    bootstrap.channel(config.epoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .group(parentGroup, childGroup);

    bootstrap.childHandler(channelInitializer);
    return bootstrap;
}

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

License:Apache License

private ServerBootstrap buildBootstrapFlashPolicy(Config config) {
    final ServerBootstrap bootstrap = new ServerBootstrap();
    parentGroup = config.epoll() ? new EpollEventLoopGroup() : new NioEventLoopGroup();
    childGroup = config.epoll() ? new EpollEventLoopGroup() : new NioEventLoopGroup();

    bootstrap.channel(config.epoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .group(parentGroup, childGroup);

    // Set up the event pipeline factory.
    bootstrap.childHandler(new FlashPolicyServerChannelInitializer());
    return bootstrap;
}

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 www.j ava2 s.  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   www .j  a va 2  s  .com*/
    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(//w  w  w. j  a  v  a 2 s  .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);
}