Example usage for io.netty.bootstrap ServerBootstrap group

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

Introduction

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

Prototype

public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) 

Source Link

Document

Set the EventLoopGroup for the parent (acceptor) and the child (client).

Usage

From source file:app.WebSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from w w  w . ja  va2 s.  com*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketServerInitializer());

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

        System.out.println("Listening on ws://0.0.0.0:" + PORT + "/ws");

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:appium.android.server.http.HttpServer.java

License:Apache License

public void start() {
    if (serverThread != null) {
        throw new IllegalStateException("Server is already running");
    }/*from  w  w w  . j  a  va  2s.  c om*/
    serverThread = new Thread() {
        @Override
        public void run() {
            EventLoopGroup bossGroup = new NioEventLoopGroup(1);
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
                bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                        .childHandler(new ServerInitializer(handlers));

                Channel ch = bootstrap.bind(port).sync().channel();
                ch.closeFuture().sync();
            } catch (InterruptedException ignored) {
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
                TrafficCounter.shutdown();
            }
        }
    };
    serverThread.start();
}

From source file:at.yawk.accordion.netty.NettyConnector.java

License:Mozilla Public License

@Override
public Server listen(SocketAddress inf) {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, BACKLOG_VALUE).childOption(ChannelOption.SO_KEEPALIVE, true);

    NettyServer server = new NettyServer(bootstrap, inf);
    server.init();//  w  w  w  . j a v  a 2 s .  c o  m

    return server;
}

From source file:baseFrame.netty.atest.HttpHelloWorldServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/* w  w  w  .j  av a 2s .  c o  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpHelloWorldServerInitializer());

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

        System.err.println("Open your web browser and navigate to " + ("http") + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:basic.TimeServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO/*from   www  .  j  ava2 s  .  c o  m*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler());
        // ???
        ChannelFuture f = b.bind(port).sync();

        // ???
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:bean.lee.demo.netty.learn.http.file.HttpStaticFileServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {// ww w  .  j av a  2 s . c o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpStaticFileServerInitializer());

        b.bind(port).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:bean.lee.demo.netty.learn.http.helloworld.HttpHelloWorldServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from ww  w. j  av a2 s  .  c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpHelloWorldServerInitializer());

        Channel ch = b.bind(port).sync().channel();
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemServerSide.java

License:Apache License

public NettyClientServerCommunicationSystemServerSide(ServerViewController controller) {
    try {/*from   ww w  .  j a  v a  2  s  .  c o  m*/

        this.controller = controller;
        /* Tulio Ribeiro */
        privKey = controller.getStaticConf().getPrivateKey();

        sessionReplicaToClient = new ConcurrentHashMap<>();
        rl = new ReentrantReadWriteLock();

        // Configure the server.

        serverPipelineFactory = new NettyServerPipelineFactory(this, sessionReplicaToClient, controller, rl);

        EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreads);
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, tcpSendBufferSize)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec)
                .option(ChannelOption.SO_BACKLOG, connectionBacklog)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(serverPipelineFactory.getDecoder());
                        ch.pipeline().addLast(serverPipelineFactory.getEncoder());
                        ch.pipeline().addLast(serverPipelineFactory.getHandler());
                    }
                }).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true);
        String myAddress;
        String confAddress = controller.getStaticConf()
                .getRemoteAddress(controller.getStaticConf().getProcessId()).getAddress().getHostAddress();

        if (InetAddress.getLoopbackAddress().getHostAddress().equals(confAddress)) {

            myAddress = InetAddress.getLoopbackAddress().getHostAddress();

        }

        else if (controller.getStaticConf().getBindAddress().equals("")) {

            myAddress = InetAddress.getLocalHost().getHostAddress();

            // If Netty binds to the loopback address, clients will not be able to connect
            // to replicas.
            // To solve that issue, we bind to the address supplied in config/hosts.config
            // instead.
            if (InetAddress.getLoopbackAddress().getHostAddress().equals(myAddress)
                    && !myAddress.equals(confAddress)) {

                myAddress = confAddress;
            }

        } else {

            myAddress = controller.getStaticConf().getBindAddress();
        }

        int myPort = controller.getStaticConf().getPort(controller.getStaticConf().getProcessId());

        ChannelFuture f = b.bind(new InetSocketAddress(myAddress, myPort)).sync();

        logger.info("ID = " + controller.getStaticConf().getProcessId());
        logger.info("N = " + controller.getCurrentViewN());
        logger.info("F = " + controller.getCurrentViewF());
        logger.info("Port (client <-> server) = "
                + controller.getStaticConf().getPort(controller.getStaticConf().getProcessId()));
        logger.info("Port (server <-> server) = "
                + controller.getStaticConf().getServerToServerPort(controller.getStaticConf().getProcessId()));
        logger.info("requestTimeout = " + controller.getStaticConf().getRequestTimeout());
        logger.info("maxBatch = " + controller.getStaticConf().getMaxBatchSize());
        if (controller.getStaticConf().getUseSignatures() == 1)
            logger.info("Using Signatures");
        else if (controller.getStaticConf().getUseSignatures() == 2)
            logger.info("Using benchmark signature verification");
        logger.info("Binded replica to IP address " + myAddress);
        // ******* EDUARDO END **************//

        /* Tulio Ribeiro */
        // SSL/TLS
        logger.info("SSL/TLS enabled, protocol version: {}",
                controller.getStaticConf().getSSLTLSProtocolVersion());

        /* Tulio Ribeiro END */

        mainChannel = f.channel();

    } catch (InterruptedException | UnknownHostException ex) {
        logger.error("Failed to create Netty communication system", ex);
    }
}

From source file:blazingcache.network.netty.NettyChannelAcceptor.java

License:Apache License

public void start() throws Exception {
    if (ssl) {//from w  w w  . j  av  a2s. c  om
        if (sslCertFile == null) {
            LOGGER.log(Level.SEVERE, "start SSL with self-signed auto-generated certificate");
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            try {
                sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).ciphers(sslCiphers)
                        .build();
            } finally {
                ssc.delete();
            }
        } else {
            LOGGER.log(Level.SEVERE, "start SSL with certificate " + sslCertFile.getAbsolutePath()
                    + " chain file " + sslCertChainFile.getAbsolutePath());
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            sslCtx = SslContextBuilder.forServer(sslCertChainFile, sslCertFile, sslCertPassword)
                    .ciphers(sslCiphers).build();
        }

    }
    if (callbackThreads == 0) {
        callbackExecutor = Executors.newCachedThreadPool();
    } else {
        callbackExecutor = Executors.newFixedThreadPool(callbackThreads, new ThreadFactory() {
            private final AtomicLong count = new AtomicLong();

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "blazingcache-callbacks-" + count.incrementAndGet());
            }
        });
    }
    bossGroup = new NioEventLoopGroup(workerThreads);
    workerGroup = new NioEventLoopGroup(workerThreads);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    NettyChannel session = new NettyChannel("unnamed", ch, callbackExecutor, null);
                    if (acceptor != null) {
                        acceptor.createConnection(session);
                    }

                    //                        ch.pipeline().addLast(new LoggingHandler());
                    // Add SSL handler first to encrypt and decrypt everything.
                    if (ssl) {
                        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
                    }

                    ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                    ch.pipeline().addLast("lengthbaseddecoder",
                            new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    //
                    ch.pipeline().addLast("messageencoder", new DataMessageEncoder());
                    ch.pipeline().addLast("messagedecoder", new DataMessageDecoder());
                    ch.pipeline().addLast(new InboundMessageHandler(session));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture f = b.bind(host, port).sync(); // (7)
    this.channel = f.channel();

}

From source file:book.netty.n4delimiterC5P1.EchoServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO/*from ww  w.j  av a2s . c  o m*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });

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

        // ???
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}