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:core.HttpServer.java

License:Apache License

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

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

From source file:cyril.server.io.LessThanNullSuite.java

License:Open Source License

public static final <C> NorthernerServer startNortherner(EventLoopGroup parentGroup, EventLoopGroup childGroup,
        int port, NorthernerService service, Authentication<C> auth, SpamListener listener) {
    ServerBootstrap b = new ServerBootstrap();
    try {//from  www .  j a va 2  s .c  om
        AuthInitializer<C> ai = new AuthInitializer<C>(service, auth, listener);
        SpamInitializer si = new SpamInitializer(ai, listener);

        b.group(parentGroup, childGroup).channel(NioServerSocketChannel.class).localAddress(port)
                .childHandler(si);

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind();

        System.out.println("Service " + service + " has gone live on port " + port);

        return new NorthernerServer(b, f);
    } finally {
        b.shutdown();
    }
}

From source file:cz.muni.csirt.seccloud.normalization.NormalizationServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    NormalizerCLI cli = new NormalizerCLI();
    CmdLineParser parser = new CmdLineParser(cli);
    try {/* www .j  a v  a  2s.c om*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        System.err.println("tcp_normalizer [options...]");
        parser.printUsage(System.err);
        System.err.println();
        // print option sample. This is useful some time
        System.err.println("Example: tcp_normalizer" + parser.printExample(OptionHandlerFilter.PUBLIC));
        System.exit(1);
    }

    Yaml yaml = new Yaml();
    Configuration config = yaml.loadAs(Files.newInputStream(Paths.get(cli.getConfig())), Configuration.class);

    final String LISTEN_ADDRESS = config.getListenAddress();
    final int LISTEN_PORT = config.getListenPort();
    final String TOPIC = config.getTopic();
    final String BOOTSTRAP_SERVERS = config.getBootstrapServers();
    final String ACKS = config.getAcks();
    final int RETRIES = config.getRetries();
    final int BATCH_SIZE = config.getBatchSize();
    final int LINGER_MS = config.getLingerMs();
    final int BUFFER_MEMORY = config.getBufferMemory();

    Producer<String, String> producer = new KafkaProducer<>(
            kafkaProperties(BOOTSTRAP_SERVERS, ACKS, RETRIES, BATCH_SIZE, LINGER_MS, BUFFER_MEMORY));

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new NormalizationServerInitializer(producer, TOPIC));

        serverBootstrap.bind(LISTEN_ADDRESS, LISTEN_PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:dbseer.middleware.server.MiddlewareServer.java

License:Apache License

public void run() throws Exception {
    // basic log info.
    Log.info(String.format("Listening port = %d", port));
    Log.info(String.format("DB log dir = %s", dbLogPath));
    Log.info(String.format("System log dir = %s", sysLogPath));

    // print server info.
    for (Server s : servers.values()) {
        s.printLogInfo();//  w  w w  .j a va2s  .c  o m
        // test MySQL/MariaDB connection using JDBC before we start anything.
        if (!s.testConnection()) {
            throw new Exception("Unable to connect to the MySQL server with the given credential.");
        } else if (!s.testMonitoringDir()) {
            throw new Exception("Specified monitoring directory and script do not exist.");
        }
    }

    // open named pipe.
    File checkPipeFile = new File(this.namedPipePath);
    if (checkPipeFile == null || !checkPipeFile.exists() || checkPipeFile.isDirectory()) {
        throw new Exception("Cannot open the named pipe for communication with dbseerroute. "
                + "You must run Maxscale with dbseerroute with correct named pipe first.");
    }

    namedPipeFile = new RandomAccessFile(this.namedPipePath, "rwd");
    if (namedPipeFile == null) {
        throw new Exception("Cannot open the named pipe for communication with dbseerroute. "
                + "You must run Maxscale with dbseerroute with correct named pipe first.");
    }

    // attach shutdown hook.
    MiddlewareServerShutdown shutdownThread = new MiddlewareServerShutdown(this);
    Runtime.getRuntime().addShutdownHook(shutdownThread);

    // let's start accepting connections.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(4);

    final MiddlewareServer server = this;
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .handler(new MiddlewareServerConnectionHandler(server))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new IdleStateHandler(10, 0, 0));
                        p.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB));
                        p.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.ZLIB));
                        p.addLast(new MiddlewarePacketDecoder());
                        p.addLast(new MiddlewarePacketEncoder());
                        p.addLast(new MiddlewareServerHandler(server));
                        //                     p.addLast(new MiddlewarePacketDecoder(), new MiddlewareServerHandler(server));
                    }
                });

        Log.info("Middleware is now accepting connections.");

        // bind and start accepting connections.
        ChannelFuture cf = b.bind(port).sync();

        // shutdown the server.
        if (cf != null) {
            cf.channel().closeFuture().sync();
        }
    } catch (Exception e) {
        Log.error(e.getMessage());
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        if (tailerExecutor != null && !tailerExecutor.isShutdown()) {
            tailerExecutor.shutdown();
        }
    }
}

From source file:de.dfki.kiara.impl.TransportServerImpl.java

License:Open Source License

@Override
public void run() throws IOException {
    int numServers = 0;
    try {/*from  www  .ja v  a2 s. c om*/
        synchronized (serverEntries) {
            for (ServerEntry serverEntry : serverEntries) {
                int port = Integer.parseInt(serverEntry.port);

                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                        .handler(new LoggingHandler(LogLevel.INFO))
                        .childHandler(serverEntry.transport.createServerChildHandler(serverEntry.listener));

                serverEntry.channel = b.bind(serverEntry.address, port).sync().channel();
                ++numServers;
            }
        }
    } catch (InterruptedException ex) {
        throw new IOException(ex);
    }
}

From source file:de.jackwhite20.cascade.server.impl.CascadeServer.java

License:Open Source License

@Override
public void start() {

    bossGroup = new NioEventLoopGroup();
    workerGroup = PipelineUtils.newEventLoopGroup(serverConfig.workerThreads(),
            new CascadeThreadFactory("Server"));

    try {//from   w ww .j  a v a  2s  .c o m
        ServerBootstrap b = new ServerBootstrap();
        serverChannel = b.group(bossGroup, workerGroup).channel(PipelineUtils.getServerChannel())
                .childHandler(new CascadeChannelInitializer(serverConfig.protocol(),
                        serverConfig.sessionListener().stream().collect(Collectors.toList())))
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_BACKLOG, 200)
                .bind(serverConfig.host(), serverConfig.port()).sync().channel();

        serverConfig.sessionListener().forEach(SessionListener::onStarted);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.jackwhite20.comix.Comix.java

License:Open Source License

public void start() {
    System.setProperty("java.net.preferIPv4Stack", "true");

    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);

    AnsiConsole.systemInstall();//  ww w.j a v  a 2 s.  c o m

    LogManager.getLogManager().reset();

    logger = new ComixLogger(consoleReader);

    logger.log(Level.INFO, "Comix", "------ Comix v.0.1 ------");

    loadConfig();

    logger.log(Level.INFO, "Load-Balancer", (targets.size() > 0) ? "Targets:" : "No Target Servers found!");
    targets.forEach(t -> logger.log(Level.INFO, "Load-Balancer",
            t.getName() + " - " + t.getHost() + ":" + t.getPort()));

    logger.log(Level.INFO, "Commands", "Registering commands...");

    registerCommands();

    logger.log(Level.INFO, "Comix", "Starting Comix on " + balancerHost + ":" + balancerPort + "...");

    balancingStrategy = new RoundRobinBalancingStrategy(targets);

    new Timer("CheckTargets").scheduleAtFixedRate(new CheckTargets(balancingStrategy), 0,
            TimeUnit.SECONDS.toMillis(comixConfig.getCheckTime()));

    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup(comixConfig.getThreads());

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_BACKLOG, comixConfig.getBacklog())
                .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.AUTO_READ, false).childOption(ChannelOption.SO_TIMEOUT, 4000)
                .childHandler(new ComixChannelInitializer());

        ChannelFuture f = bootstrap.bind(comixConfig.getPort()).sync();

        reload();

        logger.log(Level.INFO, "Comix", "Comix is started!");

        f.channel().closeFuture().sync();

        running = false;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        shutdown();
    }
}

From source file:de.jackwhite20.japs.server.JaPSServer.java

License:Open Source License

private void start() {

    if (PipelineUtils.isEpoll()) {
        LOGGER.info("Using high performance epoll event notification mechanism");
    } else {//from   w w w .jav  a 2 s .co m
        LOGGER.info("Using normal select/poll event notification mechanism");
    }

    bossGroup = PipelineUtils.newEventLoopGroup(1);
    workerGroup = PipelineUtils.newEventLoopGroup(workerThreads);

    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverChannel = serverBootstrap.group(bossGroup, workerGroup).channel(PipelineUtils.getServerChannel())
                .childHandler(new ServerChannelInitializer(this)).option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_BACKLOG, backlog).bind(new InetSocketAddress(host, port)).sync()
                .channel();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    LOGGER.log(Level.INFO, "JaPS server started on {0}:{1}", new Object[] { host, String.valueOf(port) });
}

From source file:de.jpaw.bonaparte.netty.testServer.SslServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//  w w  w  . j a  va2 s . com
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).localAddress(new InetSocketAddress(port))
                .childOption(ChannelOption.TCP_NODELAY, true).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new BonaparteNettySslPipelineFactory(1000, new TestServerHandler(), useSsl, false,
                        requirePeerAuthentication, null));

        // Start the server.
        ChannelFuture f = b.bind().sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:de.jpaw.bonaparte.netty.testServer.TestServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(3);
    EventLoopGroup workerGroup = new NioEventLoopGroup(6);
    try {/*from w  w  w .  j  a  v a  2 s . c  om*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).localAddress(new InetSocketAddress(port))
                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new BonaparteNettyPipelineFactory(1000, new TestServerHandler(), null, 1));

        // Start the server.
        ChannelFuture f = b.bind().sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } catch (Exception e) {
        System.out.println("Exception " + e + " occured");
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}