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:me.jtalk.socketconnector.io.TCPManager.java

License:Open Source License

private ServerBootstrap instantiateServer(TCPActivationSpec spec) throws ResourceException {

    ServerBootstrap newServer = new ServerBootstrap();
    newServer.group(this.listeners, this.workers);
    newServer.channel(NioServerSocketChannel.class);
    newServer.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override/*from  www  .  j av  a2  s.  c  o  m*/
        protected void initChannel(SocketChannel c) throws Exception {
            c.pipeline().addLast(new Receiver(TCPManager.this, TCPManager.this.ids.incrementAndGet()))
                    .addLast(new Sender());
        }
    });
    newServer.option(ChannelOption.SO_KEEPALIVE, true);
    newServer.option(ChannelOption.SO_BACKLOG, spec.getBacklog());
    newServer.option(ChannelOption.TCP_NODELAY, true);

    return newServer;
}

From source file:me.netty.http.HttpServer.java

License:Apache License

public void start() throws Exception {
    //?/* w  ww . ja v  a2s. c o m*/
    serverContext.initContext();

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // 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.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }
    // Configure the http2Orhttp.

    //CPU??workwork?
    // ?????
    int threads = Runtime.getRuntime().availableProcessors() * 2;

    EventLoopGroup bossGroup = new NioEventLoopGroup(threads);
    EventLoopGroup workerGroup = new NioEventLoopGroup(threads);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new Http2ServerInitializer(sslCtx));

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

        logger.info("Open your HTTP/2-enabled web browser and navigate to " + (SSL ? "https" : "http")
                + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync().addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future<? super Void> future) throws Exception {
                logger.info("service has shutdown");
            }
        });
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}

From source file:me.smoe.adar.netty.EchoNetty5.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap = bootstrap.group(bossGroup, workerGroup);
    bootstrap = bootstrap.channel(NioServerSocketChannel.class);

    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override//from   w  w  w.j  a va 2  s .  c o  m
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new EchoServerHandler());
        }
    });

    bootstrap.option(ChannelOption.SO_BACKLOG, 200);

    ChannelFuture future = bootstrap.bind(10080).sync();
    future.channel().closeFuture().sync();
}

From source file:me.zhuoran.amoeba.netty.server.HttpServer.java

License:Apache License

public void run(int eventLoopThreads, int maxContentLength) throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();// bossGroup??
    EventLoopGroup workerGroup = new NioEventLoopGroup(eventLoopThreads);// //workerGroup??boss??
    try {//from   w  w  w.ja v  a  2 s  .co  m
        //ServerBootstrap?NIO????Channel?????
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);// ?
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpServerInitializer(maxContentLength));

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

From source file:net.hasor.rsf.bootstrap.RsfBootstrap.java

License:Apache License

public RsfContext sync() throws Throwable {
    LoggerHelper.logInfo("initialize rsfBootstrap");
    if (this.rsfStart == null) {
        LoggerHelper.logInfo("create RsfStart.");
        this.rsfStart = new InnerRsfStart();
    }//from  ww w.j  a va2  s.c o m
    if (this.settings == null) {
        this.settings = new DefaultRsfSettings(new StandardContextSettings(DEFAULT_RSF_CONFIG));
        this.settings.refresh();
    }
    if (this.settings.getXmlNode("hasor.rsfConfig") == null) {
        throw new IOException("settings is not load.");
    }
    //
    //RsfContext
    LoggerHelper.logInfo("agent shutdown method on DefaultRsfContext.", DEFAULT_RSF_CONFIG);
    final DefaultRsfContext rsfContext = new DefaultRsfContext(this.settings) {
        public void shutdown() {
            LoggerHelper.logInfo("shutdown rsf.");
            super.shutdown();
            doShutdown();
        }
    };
    if (this.workMode == WorkMode.Customer) {
        return doBinder(rsfContext);
    }
    //
    //localAddress & bindSocket
    InetAddress localAddress = this.localAddress;
    if (localAddress == null) {
        localAddress = finalBindAddress(rsfContext);
    }
    int bindSocket = (this.bindSocket < 1) ? this.settings.getBindPort() : this.bindSocket;
    LoggerHelper.logInfo("bind to address = %s , port = %s.", localAddress, bindSocket);
    //Netty
    final URL hostAddress = URLUtils.toURL(localAddress.getHostAddress(), bindSocket);
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup(this.settings.getNetworkListener(),
            new NameThreadFactory("RSF-Listen-%s"));
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(bossGroup, rsfContext.getLoopGroup());
    boot.channel(NioServerSocketChannel.class);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            Channel channel = ch.pipeline().channel();
            NetworkConnection.initConnection(hostAddress, channel);
            //
            ch.pipeline().addLast(new RSFCodec(), new RsfProviderHandler(rsfContext));
        }
    }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
    ChannelFuture future = boot.bind(localAddress, bindSocket);
    final Channel serverChannel = future.channel();
    LoggerHelper.logInfo("rsf Server started at :%s:%s", localAddress, bindSocket);
    //add
    this.shutdownHook = new Runnable() {
        public void run() {
            LoggerHelper.logInfo("shutdown rsf server.");
            bossGroup.shutdownGracefully();
            serverChannel.close();
        }
    };
    //
    return doBinder(rsfContext);
}

From source file:net.ieldor.Main.java

License:Open Source License

/**
 * Initates a new gaming enviroment, here we are going to setup everything
 * needed for the server to be able to bind.
 *//*from   w  w  w  .ja va 2  s.c om*/
private void initate() {
    bootstrap = new ServerBootstrap();
    bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_BACKLOG, 100);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.handler(new LoggingHandler(LogLevel.INFO));
    bootstrap.childHandler(new ChannelChildHandler(this));
    try {
        bootstrap.localAddress(43594).bind().sync();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.jselby.pc.network.NetworkServer.java

License:Open Source License

public void run() {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {/*from   w w  w  . java  2 s  .  c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new PacketDecoder(), new ClientConnectionHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        System.out.println("Binding to port " + port + "...");
        ChannelFuture fut = b.bind("0.0.0.0", port).sync();
        this.f = fut.channel().closeFuture();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
    }
}

From source file:net.kuujo.copycat.io.transport.NettyServer.java

License:Apache License

/**
 * Starts listening for the given member.
 *//* www.j ava2s. c om*/
private void listen(Address address, Consumer<Connection> listener, Context context) {
    channelGroup = new DefaultChannelGroup("copycat-acceptor-channels", GlobalEventExecutor.INSTANCE);

    handler = new ServerHandler(connections, listener, context);

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup)
            .channel(eventLoopGroup instanceof EpollEventLoopGroup ? EpollServerSocketChannel.class
                    : NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 32, 0, 2, 0, 2));
                    pipeline.addLast(handler);
                }
            }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.ALLOCATOR, ALLOCATOR)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    LOGGER.info("Binding to {}", address);

    ChannelFuture bindFuture = bootstrap.bind(address.socketAddress());
    bindFuture.addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            listening = true;
            context.executor().execute(() -> {
                LOGGER.info("Listening at {}", bindFuture.channel().localAddress());
                listenFuture.complete(null);
            });
        } else {
            context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause()));
        }
    });
    channelGroup.add(bindFuture.channel());
}

From source file:net.kuujo.copycat.netty.NettyTcpProtocolServer.java

License:Apache License

@Override
public synchronized CompletableFuture<Void> listen() {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {/*from  ww w.j a  va 2s  .c o m*/
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (SSLException | CertificateException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    serverGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup(protocol.getThreads());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast(sslContext.newHandler(channel.alloc()));
                    }
                    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
                    pipeline.addLast("bytesDecoder", new ByteArrayDecoder());
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.addLast("bytesEncoder", new ByteArrayEncoder());
                    pipeline.addLast("handler", new ServerHandler());
                }
            }).option(ChannelOption.SO_BACKLOG, 128);

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog());

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(host, port).addListener((ChannelFutureListener) channelFuture -> {
        channelFuture.channel().closeFuture().addListener(closeFuture -> {
            workerGroup.shutdownGracefully();
        });

        if (channelFuture.isSuccess()) {
            channel = channelFuture.channel();
            future.complete(null);
        } else {
            future.completeExceptionally(channelFuture.cause());
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java

License:Apache License

@Override
public CompletableFuture<Void> start() {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    // TODO: Configure proper SSL trust store.
    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {//  ww  w  .j  av a  2s .  c om
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (SSLException | CertificateException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    final EventLoopGroup serverGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup(protocol.getThreads());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast(sslContext.newHandler(channel.alloc()));
                    }
                    pipeline.addLast(new ObjectEncoder(),
                            new ObjectDecoder(
                                    ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())),
                            new TcpProtocolServerHandler(TcpProtocolServer.this));
                }
            }).option(ChannelOption.SO_BACKLOG, 128);

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay());
    bootstrap.option(ChannelOption.SO_REUSEADDR, protocol.isReuseAddress());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive());
    bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog());

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    workerGroup.shutdownGracefully();
                }
            });

            if (channelFuture.isSuccess()) {
                channel = channelFuture.channel();
                future.complete(null);
            } else {
                future.completeExceptionally(channelFuture.cause());
            }
        }
    });
    return future;
}