Example usage for io.netty.bootstrap ServerBootstrap ServerBootstrap

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

Introduction

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

Prototype

public ServerBootstrap() 

Source Link

Usage

From source file:com.liferay.sync.engine.lan.server.file.LanFileServer.java

License:Open Source License

public void start() throws Exception {
    _childEventLoopGroup = new NioEventLoopGroup();
    _parentEventLoopGroup = new NioEventLoopGroup(1);

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverBootstrap.group(_parentEventLoopGroup, _childEventLoopGroup);
    serverBootstrap.channel(NioServerSocketChannel.class);

    _syncTrafficShapingHandler = new SyncTrafficShapingHandler(_childEventLoopGroup);

    _lanFileServerInitializer = new LanFileServerInitializer(_syncTrafficShapingHandler);

    serverBootstrap.childHandler(_lanFileServerInitializer);

    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture channelFuture = serverBootstrap.bind(PropsValues.SYNC_LAN_SERVER_PORT);

    try {//  w  w w  . java  2s. c  om
        channelFuture.sync();
    } catch (Exception e) {

        // Compiling fails when directly catching BindException. Netty seems
        // to throw an undeclared exception.

        if (e instanceof BindException) {
            channelFuture = serverBootstrap.bind(0);

            channelFuture.sync();
        } else {
            throw e;
        }
    }

    Channel channel = channelFuture.channel();

    InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.localAddress();

    _port = inetSocketAddress.getPort();

    channelFuture.sync();

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            long count = SyncFileService.getSyncFilesCount(SyncFile.UI_EVENT_DOWNLOADING,
                    SyncFile.UI_EVENT_UPLOADING);

            long writeDelay = 0;

            if (count > 0) {
                _syncTrafficShapingHandler.setWriteDelay(PropsValues.SYNC_LAN_SERVER_WRITE_DELAY);
            }

            _syncTrafficShapingHandler.setWriteDelay(writeDelay);
        }

    };

    ScheduledExecutorService scheduledExecutorService = LanEngine.getScheduledExecutorService();

    scheduledExecutorService.scheduleWithFixedDelay(runnable, 0, 500, TimeUnit.MILLISECONDS);
}

From source file:com.lin.studytest.netty.server.EchoServer.java

License:Apache License

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

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//  w  ww  .  j  av  a  2 s  .  c  om
        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 {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new EchoServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).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:com.linecorp.armeria.server.Server.java

License:Apache License

private ChannelFuture start(ServerPort port) {
    ServerBootstrap b = new ServerBootstrap();

    b.group(bossGroup, workerGroup);//from   ww w  .  ja  va  2  s.  c om
    b.channel(
            NativeLibraries.isEpollAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class);
    b.childHandler(new HttpServerPipelineConfigurator(config, port, sslContexts,
            Optional.ofNullable(gracefulShutdownHandler)));

    return b.bind(port.localAddress());
}

From source file:com.linkedin.mitm.proxy.ProxyServer.java

License:Open Source License

/**
 * Start proxy server/* ww w  .ja  v a  2  s  .  c o  m*/
 * */
public void start() throws InterruptedException {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(_acceptorGroup, _upstreamWorkerGroup);
    serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() {
        @Override
        public ServerChannel newChannel() {
            return new NioServerSocketChannel();
        }
    });
    serverBootstrap.childHandler(new ProxyInitializer(this));

    //bind
    ChannelFuture future = serverBootstrap.bind(_host, _port);

    //wait for the future
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        future.channel().closeFuture().awaitUninterruptibly();
        throw new ChannelException(String.format("Failed to bind to: %s:%d", _host, _port), future.cause());
    } else {
        _allChannels.add(future.channel());
    }
}

From source file:com.linkedin.pinot.transport.netty.NettyTCPServer.java

License:Apache License

@Override
protected ServerBootstrap getServerBootstrap() {
    ServerBootstrap b = new ServerBootstrap();
    b.group(_bossGroup, _workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(createChannelInitializer()).option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true);
    return b;//from w  w  w . j  ava  2  s.  c  o  m
}

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  w w .  j av  a 2s.c om
    }

    //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.linkedin.r2.transport.http.server.HttpNettyServer.java

License:Apache License

@Override
public void start() {
    _eventExecutors = new DefaultEventExecutorGroup(_threadPoolSize);
    _bossGroup = new NioEventLoopGroup(1, new NamedThreadFactory("R2 Nio Boss"));
    _workerGroup = new NioEventLoopGroup(0, new NamedThreadFactory("R2 Nio Worker"));

    ServerBootstrap bootstrap = new ServerBootstrap().group(_bossGroup, _workerGroup)
            .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override/* w ww  .j a v a 2 s. co  m*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                    ch.pipeline().addLast("aggregator", new HttpObjectAggregator(1048576));
                    ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                    ch.pipeline().addLast("rapi", new RAPServerCodec());
                    ch.pipeline().addLast(_eventExecutors, "handler",
                            _restOverStream ? new StreamHandler() : new RestHandler());
                }
            });

    bootstrap.bind(new InetSocketAddress(_port));
}

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  . ja  v  a2  s  . c  om
    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  ww .  j a va  2s. 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) {
    ///< ?//  ww  w. j  a v  a  2s. c  om
    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;
}