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.elasticsearch.transport.netty4.Netty4Transport.java

License:Apache License

private void createServerBootstrap(String name, Settings settings) {
    if (logger.isDebugEnabled()) {
        logger.debug(/*from w  w w . j av a2  s.  c o  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.enderstone.server.Main.java

License:Open Source License

@Override
public void run() {
    Main.instance = this;
    EnderLogger.info("Starting " + NAME + " " + VERSION + " server version " + PROTOCOL_VERSION + ".");
    EnderLogger.info("Authors: " + Arrays.asList(AUTHORS).toString());
    EnderLogger/* www  .  j  a  v a  2s .c om*/
            .info("Top contributors: " + Arrays.asList(TOP_CONTRIBUTORS).toString() + " <--- Thanks to them!");
    EnderLogger.info("Loading server.properties file...");
    this.loadConfigFromDisk();
    this.motd = (String) prop.get("motd");
    // TODO read max players from config
    // this.maxPlayers = ;
    EnderLogger.info("Loaded server.properties file!");

    EnderLogger.info("Loading favicon...");
    try {
        if (readFavicon())
            EnderLogger.info("Loaded server-icon.png!");
    } catch (FileNotFoundException e) {
        EnderLogger.info("server-icon.png not found!");
    } catch (IOException e) {
        EnderLogger.warn("Error while reading server-icon.png!");
        EnderLogger.exception(e);
    }

    EnderLogger.info("Server ready... Starting required threads now!");

    final ThreadGroup nettyListeners = new ThreadGroup(Thread.currentThread().getThreadGroup(),
            "Netty Listeners");
    for (final int nettyPort : new int[] { this.port }) {

        Thread t;
        (t = new Thread(nettyListeners, new Runnable() {

            @Override
            public void run() {
                EnderLogger.info("Started Netty Server at port " + nettyPort + "...");
                ThreadGroup group = new ThreadGroup(nettyListeners, "Listener-" + nettyPort);
                EventLoopGroup bossGroup = new NioEventLoopGroup(MAX_NETTY_BOSS_THREADS,
                        new NettyThreadFactory(group, "boss"));
                EventLoopGroup workerGroup = new NioEventLoopGroup(MAX_NETTY_WORKER_THREADS,
                        new NettyThreadFactory(group, "worker"));

                try {
                    ServerBootstrap bootstrap = new ServerBootstrap();
                    bootstrap.group(bossGroup, workerGroup);
                    bootstrap.channel(NioServerSocketChannel.class);
                    bootstrap.childHandler(new ConnectionInitializer());

                    bootstrap.bind(nettyPort).sync().channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    EnderLogger.info("Stopped Netty Server at port " + nettyPort + "...");
                    scheduleShutdown();
                    bossGroup.shutdownGracefully();
                    workerGroup.shutdownGracefully();
                }
            }
        }, "Listener-" + nettyPort)).start();
        this.listenThreads.add(t);
    }

    (mainThread = new Thread(new Runnable() {
        long lastTick = System.currentTimeMillis();

        @Override
        public void run() {
            EnderLogger.info("Main Server Thread initialized and started!");
            EnderLogger.info("" + NAME + " Server started, " + PROTOCOL_VERSION
                    + " clients can now connect to port " + port + "!");

            // TODO support multiple worlds with a simple and good working system
            worlds.add(new EnderWorld("world1", new SimpleGenerator(), new File("world1")));
            worlds.add(new EnderWorld("world2", new FlyingIslandsGenerator(), new File("world2")));

            try {
                while (Main.this.isRunning) {
                    mainServerTick();
                }
            } catch (InterruptedException e) {
                Main.this.isRunning = false;
                Thread.currentThread().interrupt();
            } catch (RuntimeException ex) {
                EnderLogger.error("CRASH REPORT! (this should not happen!)");
                EnderLogger.error("Main thread has shut down, this shouldn't happen!");
                EnderLogger.exception(ex);
                EnderLogger.error("Server was processing tick " + tick);
                EnderLogger.error("Last succesfull tick was " + new Date(lastTick).toString());
            } finally {
                Main.this.isRunning = false;
                Main.getInstance().directShutdown();
                EnderLogger.info("Main Server Thread stopped!");
            }
        }

        private void mainServerTick() throws InterruptedException {

            synchronized (sendToMainThread) {
                for (Runnable run : sendToMainThread) {
                    try {
                        run.run();
                    } catch (Exception e) {
                        EnderLogger.warn("Problem while executing task " + run.toString());
                        EnderLogger.exception(e);
                    }
                }
                sendToMainThread.clear();
            }

            try {
                serverTick(tick);
            } catch (Exception e) {
                EnderLogger.error("Problem while running ServerTick()");
                EnderLogger.exception(e);
            }
            this.lastTick += getTickTime();
            long sleepTime = (lastTick) - System.currentTimeMillis();
            Main.this.lastTickSlices[Main.this.lastTickPointer] = sleepTime;
            if (++Main.this.lastTickPointer >= Main.this.lastTickSlices.length)
                Main.this.lastTickPointer = 0;
            if (sleepTime < Main.CANT_KEEP_UP_TIMEOUT) {
                this.warn("Can't keep up! " + -(sleepTime / tickTime) + " ticks behind!");
                this.lastTick = System.currentTimeMillis();
            } else if (sleepTime > Main.MAX_SLEEP) {
                this.warn("Did the system time change?");
                this.lastTick = System.currentTimeMillis();
            } else if (sleepTime > 0) {
                Thread.sleep(sleepTime);
            } else {
                if (Thread.interrupted()) {
                    throw new InterruptedException();
                }
            }
            tick++;
        }

        public void warn(String warn) {
            EnderLogger.warn("[ServerThread] [tick-" + tick + "] " + warn);
        }
    }, "ServerThread")).start();

    ThreadGroup shutdownHooks = new ThreadGroup(Thread.currentThread().getThreadGroup(), "Shutdown hooks");
    Runtime.getRuntime().addShutdownHook(new Thread(shutdownHooks, new Runnable() {

        @Override
        public void run() {
            Main.this.scheduleShutdown();
            boolean interrupted = false;
            boolean joined = false;
            do {
                try {
                    mainThread.join();
                    joined = true;
                } catch (InterruptedException ex) {
                    interrupted = true;
                }
            } while (!joined);
            if (interrupted)
                Thread.currentThread().interrupt();
        }
    }, "Server stopping"));
}

From source file:org.ethereum.net.server.PeerServerImpl.java

License:Open Source License

public void start(int port) {
    // TODO review listening use
    listening = true;/*  w w w  .  j  a v a 2  s.  co  m*/

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, "");

    ethereumListener.trace("Listening on port " + port);

    try {
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());

        b.handler(new LoggingHandler());
        b.childHandler(ethereumChannelInitializer);

        // Start the client.
        logger.info("Listening for incoming connections, port: [{}] ", port);
        logger.info("NodeId: [{}] ", Hex.toHexString(config.nodeId()));

        ChannelFuture f = b.bind(port).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
        logger.debug("Connection is closed");

        // TODO review listening use
        listening = false;
    } catch (Exception e) {
        logger.debug("Exception: {} ({})", e.getMessage(), e.getClass().getName());
        throw new Error("Server Disconnected");
    } finally {
        workerGroup.shutdownGracefully();

    }
}

From source file:org.fusesource.hawtdispatch.netty.HawtEchoTest.java

License:Apache License

@Test
public void testSimpleEcho() throws Throwable {
    // Configure the server.
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(new HawtEventLoopGroup(Dispatch.getGlobalQueue()),
            new HawtEventLoopGroup(Dispatch.getGlobalQueue())).channel(HawtServerSocketChannel.class);

    // Configure the client.
    Bootstrap cb = new Bootstrap();
    cb.group(new HawtEventLoopGroup(Dispatch.getGlobalQueue())).channel(HawtSocketChannel.class);

    final EchoHandler sh = new EchoHandler();
    final EchoHandler ch = new EchoHandler();

    sb.childHandler(sh);
    cb.handler(ch);//w  w w  .  j a  va2s.c  o  m

    Channel sc = sb.bind(new InetSocketAddress(0)).sync().channel();
    Channel cc = cb.connect(sc.localAddress()).sync().channel();

    for (int i = 0; i < data.length;) {
        int length = Math.min(random.nextInt(1024 * 64), data.length - i);
        cc.write(Unpooled.wrappedBuffer(data, i, length));
        i += length;
    }

    while (ch.counter < data.length) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // Ignore.
        }
    }

    while (sh.counter < data.length) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // Ignore.
        }
    }

    sh.channel.close().sync();
    ch.channel.close().sync();
    sc.close().sync();

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
        throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
        throw ch.exception.get();
    }
}

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   ww  w  . j ava  2s . c om*/
    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.iotivity.cloud.base.CoapServer.java

License:Open Source License

public void startServer(InetSocketAddress inetSocketAddress)
        throws CertificateException, SSLException, InterruptedException {

    try {//from w ww  .  j a v  a  2s . co m
        ServerBootstrap b = new ServerBootstrap();
        b.group(acceptorGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new LoggingHandler(LogLevel.INFO));

        b.childHandler(initializer);

        ChannelFuture channelFuture = b.bind(inetSocketAddress).sync();

        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                // TODO Auto-generated method stub
                Logger.d("Connection status of TCP CoAP SERVER  : " + future.isSuccess());
            }
        });
    } finally {
    }
}

From source file:org.iotivity.cloud.base.HttpServer.java

License:Open Source License

public void startServer(InetSocketAddress inetSocketAddress)
        throws CertificateException, SSLException, InterruptedException {

    try {/*from   w ww .  j a v  a2 s.com*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));

        b.childHandler(initializer);

        ChannelFuture ch = b.bind(inetSocketAddress).sync();
        ch.addListener(new GenericFutureListener<ChannelFuture>() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                // TODO Auto-generated method stub
                System.out.println("Connection status of TCP Http SERVER  : " + future.isSuccess());
            }

        });
    } finally {
    }

}

From source file:org.iotivity.cloud.base.server.Server.java

License:Open Source License

public void startServer(boolean tlsMode) throws CertificateException, SSLException, InterruptedException {

    try {/*from   w  w  w .j  a  va2  s  .  co m*/
        if (tlsMode)
            Log.i("Server starts with TLS!");

        if (tlsMode == true) {

            File serverCert = new File(OICConstants.CLOUD_CERT_FILE);

            File serverKey = new File(OICConstants.CLOUD_KEY_FILE);

            mSslContext = SslContextBuilder.forServer(serverCert, serverKey).build();
        }

        ServerBootstrap b = new ServerBootstrap();
        b.group(acceptorGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));

        b.childHandler(mServerInitializer);

        b.bind(mInetSocketAddress).sync();
    } finally {
    }
}

From source file:org.jfxvnc.ui.service.VncRenderService.java

License:Apache License

private void startListening() throws Exception {
    connectProperty.set(true);//from w w  w  . java2s  . c  o  m
    shutdown();
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100);

    b.childHandler(new ProtocolInitializer(VncRenderService.this, config));

    int port = listeningPortProperty.get() > 0 ? listeningPortProperty.get() : LISTENING_PORT;
    b.bind(port).addListener(l -> {
        logger.info("wait for incoming connection request on port: {}..", port);
        connectProperty.set(l.isSuccess());
    }).sync();

}

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

License:Apache License

@Override
public ChannelFuture bind(SocketAddress localAddress) {
    ServerBootstrap boot = bootstrap();

    if (isNativeEt()) {
        boot.channelFactory(TcpChannelProvider.NATIVE_ACCEPTOR);
    } else {//from  www.  j av a2  s  . c  o  m
        boot.channelFactory(TcpChannelProvider.NIO_ACCEPTOR);
    }
    boot.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new IdleStateChecker(timer, JConstants.READER_IDLE_TIME_SECONDS, 0, 0),
                    idleStateTrigger, new ProtocolDecoder(), encoder, handler);
        }
    });

    setOptions();

    return boot.bind(localAddress);
}