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.knoxcraft.netty.server.HttpUploadServer.java

License:Apache License

public boolean enable(final Logman logger) {
    thread = new Thread() {
        public void run() {
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup);
                b.channel(NioServerSocketChannel.class);
                b.handler(new LoggingHandler(LogLevel.INFO));
                b.childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override//from ww w.j  a  va  2s  .  co  m
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();

                        pipeline.addLast(new HttpRequestDecoder());
                        // Prevents HTTP messages from being "chunked"
                        pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
                        pipeline.addLast(new HttpResponseEncoder());

                        // Remove the following line if you don't want automatic content compression.
                        pipeline.addLast(new HttpContentCompressor());

                        pipeline.addLast(new HttpUploadServerHandler(logger));
                    }
                });

                Channel ch = b.bind(PORT).sync().channel();

                ch.closeFuture().sync();
            } catch (InterruptedException e) {
                // TODO: log this server-side using logman?
                logger.error("Interrupted server thread!");
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    };
    thread.start();
    return true;
}

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

@Override
@PostConstruct//from  ww w. jav  a  2  s .  co  m
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 initSocket() throws Exception {
    ServerBootstrap b = new ServerBootstrap();
    b.group(this.management.getBossGroup(), this.management.getWorkerGroup());
    if (this.ipChannelType == IpChannelType.SCTP) {
        b.channel(NioSctpServerChannel.class);
        b.option(ChannelOption.SO_BACKLOG, 100);
        b.childHandler(new NettySctpServerChannelInitializer(this, this.management));
        this.applySctpOptions(b);
    } else {/*w  w  w.  j ava2s  .  c o  m*/
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.SO_BACKLOG, 100);
        b.childHandler(new NettyTcpServerChannelInitializer(this, this.management));
    }
    b.handler(new LoggingHandler(LogLevel.INFO));

    InetSocketAddress localAddress = new InetSocketAddress(this.hostAddress, this.hostport);

    // Bind the server to primary address.
    ChannelFuture channelFuture = b.bind(localAddress).sync();

    // Get the underlying sctp channel
    if (this.ipChannelType == IpChannelType.SCTP) {
        this.serverChannelSctp = (SctpServerChannel) channelFuture.channel();

        // Bind the secondary address.
        // Please note that, bindAddress in the client channel should be done before connecting if you have not
        // enable Dynamic Address Configuration. See net.sctp.addip_enable kernel param
        if (this.extraHostAddresses != null) {
            for (int count = 0; count < this.extraHostAddresses.length; count++) {
                String localSecondaryAddress = this.extraHostAddresses[count];
                InetAddress localSecondaryInetAddress = InetAddress.getByName(localSecondaryAddress);

                channelFuture = this.serverChannelSctp.bindAddress(localSecondaryInetAddress).sync();
            }
        }

        if (logger.isInfoEnabled()) {
            logger.info(String.format("SctpServerChannel bound to=%s ",
                    this.serverChannelSctp.allLocalAddresses()));
        }
    } else {
        this.serverChannelTcp = (NioServerSocketChannel) channelFuture.channel();

        if (logger.isInfoEnabled()) {
            logger.info(
                    String.format("ServerSocketChannel bound to=%s ", this.serverChannelTcp.localAddress()));
        }
    }
}

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  www. j  av 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   w  ww .j av a  2 s.c  om
    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.artemis.impl.moas.MoasServerController.java

License:Apache License

/**
 * Run the MOAS Servcer./*w  w  w.j  a  va  2s  . c o  m*/
 */
private void run() {
    final MoasServerController ctrl = this;
    try {
        final ServerBootstrap bootstrap = createServerBootStrap();

        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new MoasServerHandler(ctrl));
            }
        });

        channel = bootstrap.bind(port).sync();
        isRunning = true;
    } catch (Exception e) {
        log.warn(ExceptionUtils.getFullStackTrace(e));
    }
}

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

License:Apache License

/**
 * Tell controller that we're ready to accept switches loop.
 *//*from ww w  .j av  a  2  s. com*/
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);
    }

}

From source file:org.onosproject.store.cluster.messaging.impl.NettyMessagingManager.java

License:Apache License

private void startAcceptingConnections() throws InterruptedException {
    ServerBootstrap b = new ServerBootstrap();
    b.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
    b.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    b.option(ChannelOption.SO_RCVBUF, 1048576);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.group(serverGroup, clientGroup);//from ww  w . j  ava 2s .c om
    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.opendaylight.protocol.bgp.rib.impl.BGPDispatcherImpl.java

License:Open Source License

public static ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer,
        final EventLoopGroup bossGroup, final EventLoopGroup workerGroup) {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    if (Epoll.isAvailable()) {
        serverBootstrap.channel(EpollServerSocketChannel.class);
        serverBootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {//from  w  w  w  . j  a  v  a  2s  .  c o m
        serverBootstrap.channel(NioServerSocketChannel.class);
    }
    final ChannelHandler serverChannelHandler = BGPChannel.createServerChannelHandler(initializer);
    serverBootstrap.childHandler(serverChannelHandler);

    serverBootstrap.option(ChannelOption.SO_BACKLOG, Integer.valueOf(SOCKET_BACKLOG_SIZE));
    serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATER_MARK);
    serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATER_MARK);

    // Make sure we are doing round-robin processing
    serverBootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);

    if (serverBootstrap.group() == null) {
        serverBootstrap.group(bossGroup, workerGroup);
    }
    return serverBootstrap;
}

From source file:org.opendaylight.protocol.bmp.impl.BmpDispatcherImpl.java

License:Open Source License

@Override
public ChannelFuture createServer(final InetSocketAddress address, final BmpSessionListenerFactory slf,
        final Optional<KeyMapping> keys) {
    Preconditions.checkNotNull(address);
    Preconditions.checkNotNull(slf);//ww  w. j  av a 2  s  .c om

    final ServerBootstrap b = new ServerBootstrap();
    b.childHandler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(BmpDispatcherImpl.this.hf.getDecoders());
            ch.pipeline().addLast(BmpDispatcherImpl.this.sessionFactory.getSession(ch, slf));
        }
    });

    b.option(ChannelOption.SO_BACKLOG, MAX_CONNECTIONS_COUNT);
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

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

    if (keys.isPresent()) {
        if (Epoll.isAvailable()) {
            b.option(EpollChannelOption.TCP_MD5SIG, keys.get());
        } else {
            throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
        }
    }
    b.group(this.bossGroup, this.workerGroup);
    final ChannelFuture f = b.bind(address);

    LOG.debug("Initiated BMP server {} at {}.", f, address);
    return f;
}