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.flysoloing.learning.network.netty.http2.tiles.Http2Server.java

License:Apache License

public ChannelFuture start() throws Exception {
    final SslContext sslCtx = configureTLS();
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
        @Override//from   w ww.jav  a  2  s  .  c om
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new Http2OrHttpHandler());
        }
    });

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

From source file:com.flysoloing.learning.network.netty.http2.tiles.HttpServer.java

License:Apache License

public ChannelFuture start() throws Exception {
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);

    b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   w  w w  .  j a  v  a 2 s .  c  om*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new HttpRequestDecoder(), new HttpResponseEncoder(),
                            new HttpObjectAggregator(MAX_CONTENT_LENGTH), new Http1RequestHandler());
                }
            });

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

From source file:com.flysoloing.learning.network.netty.spdy.server.SpdyServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
            .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.NPN,
                    // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectorFailureBehavior.NO_ADVERTISE,
                    // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                    SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.SPDY_3_1,
                    ApplicationProtocolNames.HTTP_1_1))
            .build();//from w w w  .  j  a v  a 2s . com

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new SpdyServerInitializer(sslCtx));

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

        System.err
                .println("Open your SPDY-enabled web browser and navigate to https://127.0.0.1:" + PORT + '/');
        System.err.println("If using Chrome browser, check your SPDY sessions at chrome://net-internals/#spdy");

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

From source file:com.flysoloing.learning.network.netty.udt.echo.bytes.ByteEchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    final ThreadFactory acceptFactory = new DefaultThreadFactory("accept");
    final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
    final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory, NioUdtProvider.BYTE_PROVIDER);
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory,
            NioUdtProvider.BYTE_PROVIDER);

    // Configure the server.
    try {/*from  w w  w  .  j  a  v a  2 s.c om*/
        final ServerBootstrap boot = new ServerBootstrap();
        boot.group(acceptGroup, connectGroup).channelFactory(NioUdtProvider.BYTE_ACCEPTOR)
                .option(ChannelOption.SO_BACKLOG, 10).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    public void initChannel(final UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new ByteEchoServerHandler());
                    }
                });
        // Start the server.
        final ChannelFuture future = boot.bind(PORT).sync();
        // Wait until the server socket is closed.
        future.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        acceptGroup.shutdownGracefully();
        connectGroup.shutdownGracefully();
    }
}

From source file:com.flysoloing.learning.network.netty.udt.echo.message.MsgEchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    final ThreadFactory acceptFactory = new DefaultThreadFactory("accept");
    final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
    final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory,
            NioUdtProvider.MESSAGE_PROVIDER);
    final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, connectFactory,
            NioUdtProvider.MESSAGE_PROVIDER);

    // Configure the server.
    try {/*from  w  ww  . j a va2s  .  c  o m*/
        final ServerBootstrap boot = new ServerBootstrap();
        boot.group(acceptGroup, connectGroup).channelFactory(NioUdtProvider.MESSAGE_ACCEPTOR)
                .option(ChannelOption.SO_BACKLOG, 10).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<UdtChannel>() {
                    @Override
                    public void initChannel(final UdtChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new MsgEchoServerHandler());
                    }
                });
        // Start the server.
        final ChannelFuture future = boot.bind(PORT).sync();
        // Wait until the server socket is closed.
        future.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        acceptGroup.shutdownGracefully();
        connectGroup.shutdownGracefully();
    }
}

From source file:com.foilen.smalltools.net.netty.NettyServer.java

License:Open Source License

/**
 * Start the server.//from  ww w  . j a  v  a  2  s.  c  o  m
 *
 * @param port
 *            the port to listen on (0 for a random port ; get it with {@link #getPort()})
 * @param trustedCertificates
 *            (optional) the certificate to trust connections from
 * @param certificate
 *            (optional) the server's certificate
 * @param channelHandlerContainers
 *            the channel handlers for the incoming connections
 */
public void start(final int port, final RSATrustedCertificates trustedCertificates,
        final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) {

    AssertTools.assertNull(thread, "Server is already started");

    final CountDownLatch countDownLatch = new CountDownLatch(1);
    thread = new Thread(() -> {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(NettyCommon.EVENT_LOOP_GROUP, NettyCommon.EVENT_LOOP_GROUP);
            serverBootstrap.channel(NioServerSocketChannel.class);

            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    InetSocketAddress remoteAddress = socketChannel.remoteAddress();
                    logger.info("Got a connection from {}:{}", remoteAddress.getHostName(),
                            remoteAddress.getPort());

                    // Add sslCtx if needed
                    if (trustedCertificates != null || certificate != null) {
                        TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null
                                : RSATools.createTrustManagerFactory(trustedCertificates);
                        KeyManagerFactory keyManagerFactory = certificate == null ? null
                                : RSATools.createKeyManagerFactory(certificate);

                        CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE;
                        SslContext sslCtx = SslContext.newServerContext(SslProvider.JDK, null,
                                trustManagerFactory, null, null, null, keyManagerFactory, null, cipherFilter,
                                null, 0, 0);
                        SslHandler sslHandler = sslCtx.newHandler(socketChannel.alloc());

                        if (trustManagerFactory == null) {
                            logger.debug("Will not verify client's identity");
                        } else {
                            logger.debug("Will verify client's identity");
                            SSLEngine sslEngine = sslHandler.engine();
                            sslEngine.setNeedClientAuth(true);
                        }

                        socketChannel.pipeline().addLast(sslHandler);
                    }

                    // Add the channel handlers
                    for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) {
                        socketChannel.pipeline()
                                .addLast(ReflectionTools.instantiate(
                                        channelHandlerContainer.getChannelHandlerClass(),
                                        channelHandlerContainer.getConstructorParams()));
                    }
                }
            }) //
                    .option(ChannelOption.SO_BACKLOG, 128) //
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            bindedPort = port;
            logger.info("Server on port {} is starting...", port);
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            SocketAddress socketAddress = channelFuture.channel().localAddress();
            if (socketAddress instanceof InetSocketAddress) {
                InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress;
                bindedPort = inetSocketAddress.getPort();
            }
            logger.info("Server on port {} is started", bindedPort);
            countDownLatch.countDown();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.info("Server on port {} is interrupted", bindedPort);
        } finally {
            countDownLatch.countDown();
        }
        logger.info("Server on port {} is stopped", bindedPort);
    });
    thread.setName("Netty Server-" + bindedPort);
    thread.start();

    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        logger.error("Interrupted while waiting for the server to start");
    }
}

From source file:com.friz.audio.AudioServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    AudioServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override//from  w  ww  .  jav  a 2  s  . c  om
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(HttpServerCodec.class.getName(), new HttpServerCodec());
                    p.addLast(HttpObjectAggregator.class.getName(), new HttpObjectAggregator(65536));
                    p.addLast(ChunkedWriteHandler.class.getName(), new ChunkedWriteHandler());
                    p.addLast(AudioChannelHandler.class.getName(), new AudioChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    hub.listen(AudioRequestEvent.class, new AudioRequestEventListener());

    service.startAsync();
}

From source file:com.friz.game.GameServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    GameServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override//from  w w  w . ja va  2 s .  c om
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(LoginInitEncoder.class.getName(), new LoginInitEncoder());
                    p.addLast(LoginInitDecoder.class.getName(), new LoginInitDecoder());
                    p.addLast(GameChannelHandler.class.getName(), new GameChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);
}

From source file:com.friz.lobby.LobbyServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    LobbyServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override/*  w w  w .java 2 s  .c  o m*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(LobbyInitEncoder.class.getName(), new LobbyInitEncoder());
                    p.addLast(LobbyInitDecoder.class.getName(), new LobbyInitDecoder());
                    p.addLast(LobbyChannelHandler.class.getName(), new LobbyChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    eventHub.listen(LobbyInitRequestEvent.class, new LobbyInitEventListener());
    eventHub.listen(SocialInitRequestEvent.class, new SocialInitEventListener());
    eventHub.listen(CreationRequestEvent.class, new CreationEventListener());
    eventHub.listen(LoginRequestEvent.class, new LoginRequestEventListener());

    moduleHub.listen(ClientVersionModule.class, new ClientVersionModuleListener());
    moduleHub.listen(ClientTypeModule.class, new ClientTypeModuleListener());
}

From source file:com.friz.login.LoginServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    LoginServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override/*  www .j  a v  a  2s .  c  om*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(IdleStateHandler.class.getName(), new IdleStateHandler(15, 0, 0));
                    p.addLast(LoginChannelHandler.class.getName(), new LoginChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);
}