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:de.jackwhite20.apex.tcp.ApexSocket.java

License:Open Source License

@Override
public Channel bootstrap(EventLoopGroup bossGroup, EventLoopGroup workerGroup, String ip, int port, int backlog,
        int readTimeout, int writeTimeout) throws Exception {

    logger.info("Bootstrapping socket server");

    ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
            .channel(PipelineUtils.getServerChannel())
            .childHandler(new ApexSocketChannelInitializer(readTimeout, writeTimeout))
            .childOption(ChannelOption.AUTO_READ, false);

    if (PipelineUtils.isEpoll()) {
        bootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);

        logger.debug("Epoll mode is now level triggered");
    }/*from w ww.j  a  va2 s .  c  om*/

    return bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_BACKLOG, backlog)
            .bind(ip, port).sync().channel();
}

From source file:de.pvsnp.chat.api.connector.ChatServer.java

public void connect() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup(); // (1)

    try {/*from w  ww  .  j  av  a2 s .co  m*/
        ServerBootstrap bootstrap = new ServerBootstrap(); // (2)
        bootstrap.group(bossGroup, workerGroup); // (3)
        bootstrap.channel(NioServerSocketChannel.class);// (4)
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { // 5
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                System.out.println(
                        "Ein Computer hat sich verbunden. IP: " + channel.remoteAddress().getHostName()); // (6)
                channel.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")), // (2)
                        new LineBasedFrameDecoder(1024), // (3)
                        new StringDecoder(Charset.forName("UTF-8")), // (2)
                        new EchoServerHandler());
                c.add(channel);
                sendMassage(channel);
            }
        });// (7)
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, keepalive); // (8)
        ChannelFuture future = bootstrap.bind(port).sync(); // (9)
        System.out.println("Server gestartet!");
        future.channel().closeFuture().sync(); // (10)
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully(); // (11)
        workerGroup.shutdownGracefully(); // (11)
    }
}

From source file:fr.kissy.zergling_push.MainServer.java

License:Apache License

private void run() throws Exception {
    final ChannelGroup allPlayers = new DefaultChannelGroup("AllPlayers", GlobalEventExecutor.INSTANCE);
    final ArrayBlockingQueue<PlayerMessage> messagesQueue = new ArrayBlockingQueue<PlayerMessage>(1024);

    final World world = new World();
    final MainLoop mainLoop = new MainLoop(world, allPlayers, messagesQueue);

    ScheduledThreadPoolExecutor mainLoopExecutor = new ScheduledThreadPoolExecutor(1);
    mainLoopExecutor.scheduleAtFixedRate(mainLoop, 0, TICK_RATE, TimeUnit.MILLISECONDS);

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(16);

    try {//from   ww w .  jav a 2s  .  c o  m
        final ServerBootstrap sb = new ServerBootstrap();
        sb.childOption(ChannelOption.TCP_NODELAY, true);
        sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("http-decoder", new HttpServerCodec());
                        pipeline.addLast("http-aggregator", new HttpObjectAggregator(65536));
                        pipeline.addLast("websocket-compression", new WebSocketServerCompressionHandler());
                        pipeline.addLast("websocket-protocol",
                                new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));
                        pipeline.addLast(executorGroup, "flatbuffer-message",
                                new FlatBufferMessageHandler(world, messagesQueue));
                        pipeline.addLast("http-server", new HttpStaticFileServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        final Channel ch = sb.bind(8080).sync().channel();
        ch.closeFuture().sync();
    } catch (Exception e) {
        throw new RuntimeException("Error while running server", e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:fr.letroll.ttorrentandroid.client.io.PeerServer.java

License:Apache License

public void start() throws Exception {
    group = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(group);//from w  w  w .j  a va  2  s. c  om
    b.channel(NioServerSocketChannel.class);
    b.option(ChannelOption.SO_BACKLOG, 128);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.childHandler(new PeerServerHandshakeHandler(client));
    b.childOption(ChannelOption.SO_KEEPALIVE, true);
    // b.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES));
    if (address != null) {
        future = b.bind(address).sync();
    } else {
        BIND: {
            Exception x = new IOException("No available port for the BitTorrent client!");
            for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) {
                try {
                    future = b.bind(i).sync();
                    break BIND;
                } catch (InterruptedException e) {
                    throw e;
                } catch (Exception e) {
                    x = e;
                }
            }
            throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + ","
                    + PORT_RANGE_END + "]", x);
        }
    }
}

From source file:io.advantageous.conekt.http.impl.HttpServerImpl.java

License:Open Source License

private void applyConnectionOptions(ServerBootstrap bootstrap) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }/*from   w w  w .j  a  v a 2s  .  c o m*/
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }

    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.childOption(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());

    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
    if (options.getAcceptBacklog() != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, options.getAcceptBacklog());
    }
}

From source file:io.advantageous.conekt.net.impl.NetServerImpl.java

License:Open Source License

private void applyConnectionOptions(ServerBootstrap bootstrap) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }//from   w  w  w  . j ava 2  s  .  co  m
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.childOption(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
    if (options.getAcceptBacklog() != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, options.getAcceptBacklog());
    }
}

From source file:io.atomix.catalyst.transport.netty.NettyServer.java

License:Apache License

/**
 * Starts listening for the given member.
 *///from   w w w  .  j ava2 s  .  c o  m
private void listen(Address address, Consumer<Connection> listener, ThreadContext context) {
    channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE);

    handler = new ServerHandler(connections, listener, context, transport.properties());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(transport.eventLoopGroup()).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (transport.properties().sslEnabled()) {
                        pipeline.addFirst(
                                new SslHandler(new NettyTls(transport.properties()).initSslEngine(false)));
                    }
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0,
                            4, 0, 4));
                    pipeline.addLast(handler);
                }
            }).option(ChannelOption.SO_BACKLOG, transport.properties().acceptBacklog())
            .option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay())
            .option(ChannelOption.SO_REUSEADDR, transport.properties().reuseAddress())
            .childOption(ChannelOption.ALLOCATOR, ALLOCATOR)
            .childOption(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive());

    if (transport.properties().sendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize());
    }
    if (transport.properties().receiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize());
    }

    LOGGER.info("Binding to {}", address);

    ChannelFuture bindFuture = bootstrap.bind(address.socketAddress());
    bindFuture.addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            listening = true;
            context.executor().execute(() -> {
                LOGGER.info("Listening at {}", bindFuture.channel().localAddress());
                listenFuture.complete(null);
            });
        } else {
            context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause()));
        }
    });
    channelGroup.add(bindFuture.channel());
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

License:Apache License

private CompletableFuture<Void> startAcceptingConnections() {
    CompletableFuture<Void> future = new CompletableFuture<>();
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.SO_BACKLOG, 128);
    b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024));
    b.childOption(ChannelOption.SO_RCVBUF, 1024 * 1024);
    b.childOption(ChannelOption.SO_SNDBUF, 1024 * 1024);
    b.childOption(ChannelOption.SO_KEEPALIVE, true);
    b.childOption(ChannelOption.TCP_NODELAY, true);
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.group(serverGroup, clientGroup);/*w  w w  .jav  a  2  s . c o m*/
    b.channel(serverChannelClass);
    if (enableNettyTls) {
        b.childHandler(new SslServerCommunicationChannelInitializer());
    } else {
        b.childHandler(new BasicChannelInitializer());
    }

    // Bind and start to accept incoming connections.
    b.bind(localAddress.port()).addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            log.info("{} accepting incoming connections on port {}", localAddress.address(true),
                    localAddress.port());
            serverChannel = f.channel();
            future.complete(null);
        } else {
            log.warn("{} failed to bind to port {} due to {}", localAddress.address(true), localAddress.port(),
                    f.cause());
            future.completeExceptionally(f.cause());
        }
    });
    return future;
}

From source file:io.grpc.netty.NettyServer.java

License:Apache License

@Override
public void start(ServerListener serverListener) throws IOException {
    listener = checkNotNull(serverListener, "serverListener");

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);//from   ww w. j ava  2  s .  co m
    b.channelFactory(channelFactory);
    // For non-socket based channel, the option will be ignored.
    b.option(SO_BACKLOG, 128);
    b.childOption(SO_KEEPALIVE, true);

    if (channelOptions != null) {
        for (Map.Entry<ChannelOption<?>, ?> entry : channelOptions.entrySet()) {
            @SuppressWarnings("unchecked")
            ChannelOption<Object> key = (ChannelOption<Object>) entry.getKey();
            b.childOption(key, entry.getValue());
        }
    }

    b.childHandler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel ch) {

            ChannelPromise channelDone = ch.newPromise();

            long maxConnectionAgeInNanos = NettyServer.this.maxConnectionAgeInNanos;
            if (maxConnectionAgeInNanos != MAX_CONNECTION_AGE_NANOS_DISABLED) {
                // apply a random jitter of +/-10% to max connection age
                maxConnectionAgeInNanos = (long) ((.9D + Math.random() * .2D) * maxConnectionAgeInNanos);
            }

            NettyServerTransport transport = new NettyServerTransport(ch, channelDone, protocolNegotiator,
                    streamTracerFactories, transportTracerFactory.create(), maxStreamsPerConnection,
                    flowControlWindow, maxMessageSize, maxHeaderListSize, keepAliveTimeInNanos,
                    keepAliveTimeoutInNanos, maxConnectionIdleInNanos, maxConnectionAgeInNanos,
                    maxConnectionAgeGraceInNanos, permitKeepAliveWithoutCalls, permitKeepAliveTimeInNanos);
            ServerTransportListener transportListener;
            // This is to order callbacks on the listener, not to guard access to channel.
            synchronized (NettyServer.this) {
                if (channel != null && !channel.isOpen()) {
                    // Server already shutdown.
                    ch.close();
                    return;
                }
                // `channel` shutdown can race with `ch` initialization, so this is only safe to increment
                // inside the lock.
                eventLoopReferenceCounter.retain();
                transportListener = listener.transportCreated(transport);
            }

            /**
             * Releases the event loop if the channel is "done", possibly due to the channel closing.
             */
            final class LoopReleaser implements ChannelFutureListener {
                private boolean done;

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!done) {
                        done = true;
                        eventLoopReferenceCounter.release();
                    }
                }
            }

            transport.start(transportListener);
            ChannelFutureListener loopReleaser = new LoopReleaser();
            channelDone.addListener(loopReleaser);
            ch.closeFuture().addListener(loopReleaser);
        }
    });
    // Bind and start to accept incoming connections.
    ChannelFuture future = b.bind(address);
    try {
        future.await();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Interrupted waiting for bind");
    }
    if (!future.isSuccess()) {
        throw new IOException("Failed to bind", future.cause());
    }
    channel = future.channel();
    Future<?> channelzFuture = channel.eventLoop().submit(new Runnable() {
        @Override
        public void run() {
            InternalInstrumented<SocketStats> listenSocket = new ListenSocket(channel);
            listenSocketStats.set(listenSocket);
            channelz.addListenSocket(listenSocket);
        }
    });
    try {
        channelzFuture.await();
    } catch (InterruptedException ex) {
        throw new RuntimeException("Interrupted while registering listen socket to channelz", ex);
    }
}

From source file:io.hekate.network.netty.NettyServer.java

License:Apache License

private void setChildOpts(ServerBootstrap boot) {
    boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    setChildUserOpt(boot, ChannelOption.TCP_NODELAY, tcpNoDelay);
    setChildUserOpt(boot, ChannelOption.SO_RCVBUF, soReceiveBufferSize);
    setChildUserOpt(boot, ChannelOption.SO_SNDBUF, soSendBuffer);
}