Example usage for io.netty.channel ChannelOption SO_BACKLOG

List of usage examples for io.netty.channel ChannelOption SO_BACKLOG

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption SO_BACKLOG.

Prototype

ChannelOption SO_BACKLOG

To view the source code for io.netty.channel ChannelOption SO_BACKLOG.

Click Source Link

Usage

From source file:com.github.unafraid.signer.server.ServerManager.java

License:Apache License

private void init() {
    SslContext sslCtx = null;/*from   ww  w . ja v  a2 s . com*/
    if (SSL) {
        try {
            final SelfSignedCertificate ssc = new SelfSignedCertificate("localhost");
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (Exception e) {
            LOGGER.warn(e.getMessage(), e);
        }
    }

    InetAddress listenAddress;
    try {
        listenAddress = Inet4Address.getByName(HOSTNAME);
    } catch (Exception e) {
        LOGGER.warn("Incorrect listen ip specified: {} using localhost instead!", HOSTNAME);
        listenAddress = Inet4Address.getLoopbackAddress();
    }
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        final ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ServerInitializer(sslCtx));

        // Start listening
        final Channel ch = b.bind(listenAddress, PORT).sync().channel();

        LOGGER.info("Open your web browser and navigate to {}://{}{}/", (SSL ? "https" : "http"),
                listenAddress.getHostAddress(), (PORT != 443 && PORT != 80 ? ":" + PORT : ""));

        // Block til closed
        ch.closeFuture().sync();

    } catch (Exception e) {
        LOGGER.warn("Failed to initialize server: ", e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.vitrifiedcode.javautilities.netty.DiscardServer.java

License:Open Source License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from w  ww  .jav a2s.co  m*/
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new DiscardServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

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

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.github.wangshuwei5.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO/*  w w w  . ja  v  a  2s  .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 NettyServerInitializer(SSLMODE.CSA.toString()));

        // ???
        ChannelFuture f = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();

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

        System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.zk1931.jzab.NettyTransport.java

License:Apache License

/**
 * Constructs a NettyTransport object./*from   ww  w .  ja v a 2 s.co  m*/
 *
 * @param hostPort "hostname:port" string. The netty transport binds to the
 *                 port specified in the string.
 * @param receiver receiver callback.
 * @param sslParam Ssl parameters.
 * @param dir the directory used to store the received file.
 */
public NettyTransport(String hostPort, final Receiver receiver, ZabConfig.SslParameters sslParam,
        final File dir) throws InterruptedException, GeneralSecurityException, IOException {
    super(receiver);
    this.keyStore = sslParam.getKeyStore();
    this.trustStore = sslParam.getTrustStore();
    this.keyStorePassword = sslParam.getKeyStorePassword() != null
            ? sslParam.getKeyStorePassword().toCharArray()
            : null;
    this.trustStorePassword = sslParam.getTrustStorePassword() != null
            ? sslParam.getTrustStorePassword().toCharArray()
            : null;
    this.dir = dir;
    if (isSslEnabled()) {
        initSsl();
    }

    this.hostPort = hostPort;
    String[] address = hostPort.split(":", 2);
    int port = Integer.parseInt(address[1]);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    if (isSslEnabled()) {
                        SSLEngine engine = serverContext.createSSLEngine();
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(true);
                        ch.pipeline().addLast(new SslHandler(engine));
                    }
                    // Incoming handlers
                    ch.pipeline().addLast(new MainHandler());
                    ch.pipeline().addLast(new ServerHandshakeHandler());
                    ch.pipeline().addLast(new NotifyHandler());
                    ch.pipeline().addLast(new ServerErrorHandler());
                }
            });

    // Travis build fails once in a while because it fails to bind to a port.
    // This is most likely a transient failure. Retry binding for 5 times with
    // 1 second sleep in between before giving up.
    int bindRetryCount = 5;
    for (int i = 0;; i++) {
        try {
            channel = b.bind(port).sync().channel();
            LOG.info("Server started: {}", hostPort);
            return;
        } catch (Exception ex) {
            if (i >= bindRetryCount) {
                throw ex;
            }
            LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort);
            Thread.sleep(1000);
        }
    }
}

From source file:com.github.zk1931.jzab.transport.NettyTransport.java

License:Apache License

/**
 * Constructs a NettyTransport object.//from  w  w w  .  ja va2s  .  c o  m
 *
 * @param hostPort "hostname:port" string. The netty transport binds to the
 *                 port specified in the string.
 * @param receiver receiver callback.
 * @param sslParam Ssl parameters.
 * @param dir the directory used to store the received file.
 */
public NettyTransport(String hostPort, final Receiver receiver, SslParameters sslParam, final File dir)
        throws InterruptedException, GeneralSecurityException, IOException {
    super(receiver);
    this.keyStore = sslParam.getKeyStore();
    this.trustStore = sslParam.getTrustStore();
    this.keyStorePassword = sslParam.getKeyStorePassword() != null
            ? sslParam.getKeyStorePassword().toCharArray()
            : null;
    this.trustStorePassword = sslParam.getTrustStorePassword() != null
            ? sslParam.getTrustStorePassword().toCharArray()
            : null;
    this.dir = dir;
    if (isSslEnabled()) {
        initSsl();
    }

    this.hostPort = hostPort;
    String[] address = hostPort.split(":", 2);
    int port = Integer.parseInt(address[1]);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    if (isSslEnabled()) {
                        SSLEngine engine = serverContext.createSSLEngine();
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(true);
                        ch.pipeline().addLast(new SslHandler(engine));
                    }
                    // Incoming handlers
                    ch.pipeline().addLast(new MainHandler());
                    ch.pipeline().addLast(new ServerHandshakeHandler());
                    ch.pipeline().addLast(new NotifyHandler());
                    ch.pipeline().addLast(new ErrorHandler());
                    // Outgoing handlers.
                    ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
                }
            });

    // Travis build fails once in a while because it fails to bind to a port.
    // This is most likely a transient failure. Retry binding for 5 times with
    // 1 second sleep in between before giving up.
    int bindRetryCount = 5;
    for (int i = 0;; i++) {
        try {
            channel = b.bind(port).sync().channel();
            LOG.info("Server started: {}", hostPort);
            return;
        } catch (Exception ex) {
            if (i >= bindRetryCount) {
                throw ex;
            }
            LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort);
            Thread.sleep(1000);
        }
    }
}

From source file:com.google.cloud.pubsub.proxy.moquette.NettyAcceptor.java

License:Open Source License

private void initFactory(String host, int port, final PipelineInitializer pipeliner) {
    ServerBootstrap bootsrap = new ServerBootstrap();
    bootsrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  w  w w.  j  a va 2 s .c  o  m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    try {
                        pipeliner.init(pipeline);
                    } catch (Throwable th) {
                        LOG.error("Severe error during pipeline creation", th);
                        throw th;
                    }
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        // Bind and start to accept incoming connections.
        ChannelFuture future = bootsrap.bind(host, port);
        LOG.info("Server binded host: {}, port: {}", host, port);
        future.sync();
    } catch (InterruptedException ex) {
        LOG.error(null, ex);
    }
}

From source file:com.grillecube.engine.network.server.ServerNetwork.java

public void start() throws Exception {
    this._bossgroup = new NioEventLoopGroup();
    this._workergroup = new NioEventLoopGroup();
    this._bootstrap = new ServerBootstrap();
    this._bootstrap.group(this._bossgroup, this._workergroup);
    this._bootstrap.channel(NioServerSocketChannel.class);
    this._bootstrap.childHandler(this);
    this._bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    this._bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    this._channel = this._bootstrap.bind(this._port).sync(); // (7)
    Logger.get().log(Level.FINE, "Listening on " + this._port);
    this.stop();//from   ww w .j a v  a 2s. c  o m
}

From source file:com.grillecube.server.network.ServerNetwork.java

public void start() throws Exception {
    this.bossgroup = new NioEventLoopGroup();
    this.workergroup = new NioEventLoopGroup();
    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(this.bossgroup, this.workergroup);
    this.bootstrap.channel(NioServerSocketChannel.class);
    this.bootstrap.childHandler(this);
    this.bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    this.bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    this.channel = this.bootstrap.bind(this.port).sync(); // (7)
    Logger.get().log(Level.FINE, "Listening on " + this.port);
    this.stop();//  w  w  w  . j  av  a 2 s.c om
}

From source file:com.gxkj.demo.netty.echo.EchoServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/* w ww  . jav  a2 s.  c o m*/
        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 {
                        ch.pipeline().addLast(
                                //new LoggingHandler(LogLevel.INFO),
                                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.hazelcast.openshift.TunnelClient.java

License:Open Source License

public ServerBootstrap createBootstrap(int localPort) throws Exception {
    System.out.println(// w  w w .  j av a  2  s . c o  m
            "Creating clientside plain-socket: (" + localPort + ") => (" + httpHost + ":" + httpPort + ")");
    return new ServerBootstrap().option(ChannelOption.SO_BACKLOG, 20).group(getBossGroup(), getWorkerGroup())
            .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(new TunnelServerConnector(getWorkerGroup(), httpHost, httpPort, httpSsl));
                }
            });

}