Example usage for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup

List of usage examples for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup

Introduction

In this page you can find the example usage for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup.

Prototype

public NioEventLoopGroup(ThreadFactory threadFactory) 

Source Link

Document

Create a new instance using the default number of threads, the given ThreadFactory and the SelectorProvider which is returned by SelectorProvider#provider() .

Usage

From source file:afred.javademo.proxy.rpc.ObjectEchoServer.java

License:Apache License

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

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w ww.j  a  va 2s.  co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                new ObjectEchoServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        b.bind(8080).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:alluxio.network.protocol.RPCMessageIntegrationTest.java

License:Apache License

@BeforeClass
public static void beforeClass() {
    sEventClient = new NioEventLoopGroup(1);
    sEventServer = new NioEventLoopGroup(1);
    sIncomingHandler = new MessageSavingHandler();

    // Setup the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(sEventServer);//  w  ww .j  a  v  a 2  s .co m
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new PipelineInitializer(sIncomingHandler));

    InetSocketAddress address = new InetSocketAddress(NetworkAddressUtils.getLocalHostName(100),
            Constants.DEFAULT_MASTER_PORT);
    ChannelFuture cf = bootstrap.bind(address).syncUninterruptibly();
    sLocalAddress = cf.channel().localAddress();

    // Setup the client.
    sBootstrapClient = new Bootstrap();
    sBootstrapClient.group(sEventClient);
    sBootstrapClient.channel(NioSocketChannel.class);
    sBootstrapClient.handler(new PipelineInitializer(new MessageSavingHandler()));
}

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 ww  w  . j  a v  a2 s .  co m
        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");
    }// w ww.j av  a  2s.  c  o  m
    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: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 {//from   ww  w  .  j av a 2  s. co  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:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java

License:Apache License

public NettyClientServerCommunicationSystemClientSide(int clientId, ClientViewController controller) {
    super();// w  w  w .ja  va2  s  . c o m

    this.clientId = clientId;
    this.workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    try {

        this.secretKeyFactory = TOMUtil.getSecretFactory();

        this.controller = controller;

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

        this.listener = new SyncListener();
        this.rl = new ReentrantReadWriteLock();

        int[] currV = controller.getCurrentViewProcesses();

        for (int i = 0; i < currV.length; i++) {
            int replicaId = currV[i];
            try {

                ChannelFuture future = connectToReplica(replicaId, secretKeyFactory);

                logger.debug("ClientID {}, connecting to replica {}, at address: {}", clientId, replicaId,
                        controller.getRemoteAddress(replicaId));

                future.awaitUninterruptibly();

                if (!future.isSuccess()) {
                    logger.error("Impossible to connect to " + replicaId);
                }

            } catch (java.lang.NullPointerException ex) {
                // What is this??? This is not possible!!!
                logger.debug("Should fix the problem, and I think it has no other implications :-), "
                        + "but we must make the servers store the view in a different place.");
            } catch (Exception ex) {
                logger.error("Failed to initialize MAC engine", ex);
            }
        }
    } catch (NoSuchAlgorithmException ex) {
        logger.error("Failed to initialize secret key factory", ex);
    }
}

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

License:Apache License

public NettyClientServerCommunicationSystemServerSide(ServerViewController controller) {
    try {/*from  w w w  . ja 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) {/*www . j  a v a 2  s  .co m*/
        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:bridgempp.bot.wrapper.BotWrapper.java

/**
 * @param args/* w  ww  .  j ava2s .  c  om*/
 *            the command line arguments
 */
public static void main(String[] args) {
    EventLoopGroup loopGroup = new NioEventLoopGroup(2);
    bootstrap = new Bootstrap();
    bootstrap.group(loopGroup);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel channel) throws Exception {

        }
    });
    File botsDir = new File("bots/");
    if (!botsDir.exists()) {
        botsDir.mkdir();
        Properties exampleBotProperties = new Properties();
        try {
            writeDefaultConfig(exampleBotProperties);
            exampleBotProperties.store(new FileOutputStream("bots/exampleBot.config"),
                    "Bot Wrapper Configuration");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Created Example Config. Please Edit");
        return;
    }
    for (File botConfig : botsDir.listFiles()) {
        botInitialize(botConfig);
    }

}

From source file:c5db.C5DB.java

License:Apache License

@Override
protected void doStart() {
    try {//from  w  ww. ja  v a 2s .com
        // TODO this should be done as part of the log file service startup, if at all.
        new LogFileService(configDirectory.getBaseConfigPath()).clearAllLogs();
    } catch (IOException e) {
        notifyFailed(e);
    }

    try {
        serverFiber = new ThreadFiber(new RunnableExecutorImpl(), "C5-Server", false);
        int processors = Runtime.getRuntime().availableProcessors();
        executor = Executors.newFixedThreadPool(processors);
        fiberPool = new PoolFiberFactory(executor);
        bossGroup = new NioEventLoopGroup(processors / 3);
        workerGroup = new NioEventLoopGroup(processors / 3);

        commandChannel.subscribe(serverFiber, message -> {
            try {
                processCommandMessage(message);
            } catch (Exception e) {
                LOG.warn("exception during message processing", e);
            }
        });

        commandRequests.subscribe(serverFiber, this::processCommandRequest);

        serviceRegisteredChannel.subscribe(serverFiber, this::onModuleStateChange);

        serverFiber.start();

        notifyStarted();
    } catch (Exception e) {
        notifyFailed(e);
    }
}