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:com.linkedin.proxy.main.ProxyServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    //process command line
    if (processCommandLine(args) == false) {
        m_log.fatal("Command line processing error. Closing...");
        return;/*w  ww  .j  ava  2s . co  m*/
    }

    //process properties file
    Properties prop = getProperties(PROP_FILE);
    if (prop == null) {
        m_log.fatal("Error in processing properties file. Closing...");
        return;
    }

    //set mode
    ProxyMode runMode;
    String temp = prop.getProperty(FLAG_PROXY_MODE);
    if (temp == null) {
        m_log.fatal("Mode is missing. Closing...");
        return;
    } else if (temp.equals("mysql")) {
        runMode = ProxyMode.MYSQL;
    } else if (temp.equals("rocksdb")) {
        runMode = ProxyMode.ROCKSDB;
    } else {
        m_log.fatal("Unknown mode " + temp + ". Closing...");
        return;
    }

    //Process mode specific files
    Set<String> dbSet = new HashSet<String>();
    if (runMode == ProxyMode.ROCKSDB) {
        //for rocksdb, I need db names
        if (DB_SET_FILE.equals("")) {
            m_log.fatal("DB set file is missing. Closing...");
            return;
        } else if (processDbSet(dbSet, DB_SET_FILE) == false) {
            m_log.fatal("Error in processing Dbset file. Closing...");
            return;
        } else {
            m_log.info("DB set file is processed");
        }
    } else {
        m_log.fatal("Unknown mode " + runMode + ". Closing...");
        return;
    }

    //perform mode based initializations if any
    if (runMode == ProxyMode.ROCKSDB) {
        RocksDB.loadLibrary();
    }

    //get run time
    int runTime;
    temp = prop.getProperty(FLAG_PROXY_RUNTIME);
    if (temp == null) {
        runTime = 0;
    } else {
        runTime = Integer.parseInt(temp);
    }
    m_log.info("Runtime is " + runTime);

    //get thread pool size
    int thrSize;
    temp = prop.getProperty(FLAG_PROXY_THR);
    if (temp == null) {
        m_log.warn("Thread pool size parameter is missing. It is set to 10 by default");
        thrSize = 10;
    } else {
        thrSize = Integer.parseInt(temp);
    }

    //get listening port
    int port;
    temp = prop.getProperty(FLAG_PROXY_PORT);
    if (temp == null) {
        m_log.fatal("Listening port is not specified. Closing...");
        return;
    } else {
        port = Integer.parseInt(temp);
    }

    //init thread pools
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup(thrSize);

    //create connection pools
    if (runMode == ProxyMode.ROCKSDB) {
        connPool = new BlockingRocksdbConnectionPool(dbSet);
    } else if (runMode == ProxyMode.MYSQL) {
        connPool = new BlockingMysqlConnectionPool();
    } else {
        m_log.fatal("Unkown setup. Closing...");
        return;
    }

    //init connection pool
    if (connPool.init(prop) == false) {
        m_log.fatal("Cannot init conn pool. Closing...");
        return;
    }

    //if run time is specified, then start closing thread
    Thread closingThread = null;
    if (runTime > 0) {
        closingThread = new ClosingThread(runTime);
        closingThread.start();

        System.out.println("Closing in " + runTime + " seconds.");
    } else {
        System.out.println("Type \"close\" to close proxy.");
    }

    try {
        ServerBootstrap b = new ServerBootstrap();

        if (runMode == ProxyMode.MYSQL) {
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new MysqlInitializer(prop, connPool));
        } else if (runMode == ProxyMode.ROCKSDB) {
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new RocksdbInitializer(prop, connPool));
        }

        ch = b.bind(port).sync().channel();

        if (runTime > 0) {
            ch.closeFuture().sync();
        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String line = in.readLine();
                m_log.debug("Got line: " + line);

                if (line == null || "close".equals(line.toLowerCase())) {
                    break;
                }
            }
        }
    } catch (Exception e) {
        m_log.error("Error..", e);
    } finally {
        close();
    }
}

From source file:com.liusu.tcp.proxy.mine.server.ReadBackServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO/*from  w  ww. j  av a  2  s  .co  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.addListener(ChannelFutureListener.CLOSE);
        // ???
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.lm.WebSocketServer.java

License:Apache License

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

    try (InputStream resourceAsStream = WebSocketServer.class.getResourceAsStream("/project.properties")) {
        PROPERTIES.load(resourceAsStream);
    } catch (IOException e) {
        e.printStackTrace();//from w w w .  j  ava 2  s  . com
    }

    if (args.length > 0) {
        PROPERTIES.setProperty("port", args[0]);
    }

    if (args.length > 1) {
        PROPERTIES.setProperty("access_key", args[1]);
    }

    setLogConfig("file".equals(PROPERTIES.getProperty("log")));

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                //        .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new WebSocketServerInitializer(sslCtx));

        int port = Integer.parseInt(PROPERTIES.getProperty("port", "8080"));
        Channel ch = b.bind(port).sync().channel();

        Console con = System.console();
        if (con != null) {
            while (ch.isOpen()) {
                String s = System.console().readLine().toLowerCase();
                switch (s) {
                case "logtofile":
                    setLogConfig(true);
                    break;
                case "logtoconsole":
                    setLogConfig(false);
                    break;
                case "exit":
                    for (Channel channel : CLIENT_NAMES.keySet()) {
                        channel.writeAndFlush(
                                new TextWebSocketFrame("03:  "));
                    }
                    ch.close();
                    break;
                }
            }
        }
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.lxd.server.AdamServer.java

License:Open Source License

private boolean netStart(int prot) {
    ///< ?/* w  w w .  j a v a2  s  .  c  o  m*/
    EventLoopGroup listenGroup = new NioEventLoopGroup(1);
    ///< 
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        ///< ??
        bootstrap.group(listenGroup, workerGroup).channel(NioServerSocketChannel.class)
                ///< , ?? INFO
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ServerInitalizer());

        ///< ?
        try {
            bootstrap.bind(prot).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    } finally {
        ///< 
        try {
            listenGroup.shutdownGracefully().sync();
            workerGroup.shutdownGracefully().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    return true;
}

From source file:com.lxz.talk.websocketx.server.WebSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from w  ww .  j  ava2  s .c om*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new WebSocketServerInitializer(sslCtx));

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

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

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

From source file:com.mapple.http.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 a va  2s  . c  o m
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 32);
        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:com.mapr.franz.netty.FranzServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap();
    try {/*w w  w . j a  va 2 s .c o  m*/
        b.group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).localAddress(new InetSocketAddress(port))
                .childOption(ChannelOption.TCP_NODELAY, true).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new FranzServerHandler());
                    }
                });

        // 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.
        b.shutdown();
    }
}

From source file:com.mastfrog.acteur.server.ServerImpl.java

License:Open Source License

@Override
public ServerControl start(int port) throws IOException {
    this.port = port;
    try {/*from  w ww  . jav a2 s.  c  o m*/
        final ServerControlImpl result = new ServerControlImpl(port);
        ServerBootstrap bootstrap = bootstrapProvider.get();

        String bindAddress = settings.getString("bindAddress");
        InetAddress addr = null;
        if (bindAddress != null) {
            addr = InetAddress.getByName(bindAddress);
        }

        bootstrap.group(result.events, result.workers).channel(NioServerSocketChannel.class)
                .childHandler(pipelineFactory);
        if (addr == null) {
            bootstrap = bootstrap.localAddress(new InetSocketAddress(port));
        } else {
            bootstrap = bootstrap.localAddress(addr, port);
        }

        localChannel = bootstrap.bind().sync().channel();
        System.err.println("Starting " + this);

        final CountDownLatch afterStart = new CountDownLatch(1);
        if (settings.getBoolean(ServerModule.SETTINGS_KEY_CORS_ENABLED, true)) {
            app.get().enableDefaultCorsHandling();
        }
        result.events.submit(new Runnable() {

            @Override
            public void run() {
                // Ensure a server is not held in memory if it has been
                // gc'd
                registry.add(new WeakRunnable(result));
                afterStart.countDown();
            }
        });
        afterStart.await();
        // Bind and start to accept incoming connections.
        return result;
    } catch (InterruptedException ex) {
        return Exceptions.chuck(ex);
    }
}

From source file:com.mastfrog.scamper.ChannelConfigurer.java

License:Open Source License

/**
 * Initialize a server sctp channel/* www.  j a v a  2  s  .  c om*/
 *
 * @param b The bootstrap
 * @return The bootstrap
 */
protected ServerBootstrap init(ServerBootstrap b) {
    b = b.group(group, worker).channel(NioSctpServerChannel.class).option(ChannelOption.SO_BACKLOG, 1000)
            .option(ChannelOption.ALLOCATOR, alloc).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(init);
    return b;
}

From source file:com.mc.netty.server.NettyServer.java

License:Open Source License

private ServerBootstrap getDefaultServerBootstrap() {
    ServerBootstrap bootStrap = new ServerBootstrap();
    bootStrap.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 1000)
            // ???
            .option(ChannelOption.SO_SNDBUF, 32 * 1024).option(ChannelOption.SO_RCVBUF, 32 * 1024)
            .option(ChannelOption.TCP_NODELAY, true)
            // ???
            .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
            .channel(NioServerSocketChannel.class).childOption(ChannelOption.SO_KEEPALIVE, true);

    return bootStrap;
}