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:jetty.cdi.CDINettyJaxrsServer.java

License:Apache License

@Override
public void start() {
    eventLoopGroup = new NioEventLoopGroup(ioWorkerCount);
    eventExecutor = new NioEventLoopGroup(executorThreadCount);
    deployment.start();//from w w  w.j  a v  a 2s.c om
    // this is the only line that's different in the whole class.
    final RequestDispatcher dispatcher = this.createRequestDispatcher();
    // Configure the server.
    if (sslContext == null) {
        bootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpRequestDecoder());
                        ch.pipeline().addLast(new HttpObjectAggregator(maxRequestSize));
                        ch.pipeline().addLast(new HttpResponseEncoder());
                        ch.pipeline().addLast(new RestEasyHttpRequestDecoder(dispatcher.getDispatcher(), root,
                                RestEasyHttpRequestDecoder.Protocol.HTTP));
                        ch.pipeline().addLast(new RestEasyHttpResponseEncoder(dispatcher));
                        ch.pipeline().addLast(eventExecutor, new RequestHandler(dispatcher));
                    }
                }).option(ChannelOption.SO_BACKLOG, backlog).childOption(ChannelOption.SO_KEEPALIVE, true);
    } else {
        final SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        bootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addFirst(new SslHandler(engine));
                        ch.pipeline().addLast(new HttpRequestDecoder());
                        ch.pipeline().addLast(new HttpObjectAggregator(maxRequestSize));
                        ch.pipeline().addLast(new HttpResponseEncoder());
                        ch.pipeline().addLast(new RestEasyHttpRequestDecoder(dispatcher.getDispatcher(), root,
                                RestEasyHttpRequestDecoder.Protocol.HTTPS));
                        ch.pipeline().addLast(new RestEasyHttpResponseEncoder(dispatcher));
                        ch.pipeline().addLast(eventExecutor, new RequestHandler(dispatcher));

                    }
                }).option(ChannelOption.SO_BACKLOG, backlog).childOption(ChannelOption.SO_KEEPALIVE, true);
    }

    bootstrap.bind(port).syncUninterruptibly();
}

From source file:jj.http.server.HttpServer.java

License:Apache License

private void makeServerBootstrap(int bindingCount) {
    serverBootstrap = new ServerBootstrap()
            .group(new NioEventLoopGroup(bindingCount, threadFactory), ioEventLoopGroup)
            .channel(NioServerSocketChannel.class).childHandler(initializer)
            .option(ChannelOption.SO_KEEPALIVE, configuration.keepAlive())
            .option(ChannelOption.SO_REUSEADDR, configuration.reuseAddress())
            .option(ChannelOption.TCP_NODELAY, configuration.tcpNoDelay())
            .option(ChannelOption.SO_TIMEOUT, configuration.timeout())
            .option(ChannelOption.SO_BACKLOG, configuration.backlog())
            .option(ChannelOption.SO_RCVBUF, configuration.receiveBufferSize())
            .option(ChannelOption.SO_SNDBUF, configuration.sendBufferSize());
}

From source file:jun.flume.netty.http.HTTPSource.java

License:Apache License

@Override
public void start() {
    Preconditions.checkState(srv == null, "Running HTTP Server found in source: " + getName()
            + " before I started one." + "Will not attempt to start.");
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    LOG.info("HTTP Server in source:" + getName() + " starting...");
    srv = new ServerBootstrap();

    try {/*  w w w.  j  a va  2s  .  c  o  m*/
        srv.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpRequestDecoder());
                        ch.pipeline().addLast(new HttpObjectAggregator(nettyHttpObjectAggregatorMaxLength));
                        ch.pipeline().addLast(new HttpResponseEncoder());
                        ch.pipeline().addLast(new ResponseHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        t = new Thread() {
            @Override
            public void run() {
                try {
                    f = srv.bind(host, port).sync();
                    f.channel().closeFuture().sync();
                } catch (InterruptedException ex) {
                    LOG.warn("Thread interrupted... ");
                } catch (Exception ex) {
                    LOG.error("Error while starting HTTPSource. Exception follows.", ex);
                    Throwables.propagate(ex);
                } finally {
                    workerGroup.shutdownGracefully();
                    bossGroup.shutdownGracefully();
                }
            }
        };

        t.start();
        LOG.info("HTTP Server in source:" + getName() + " started...");
    } catch (Exception ex) {
        LOG.error("Error while starting HTTPSource. Exception follows.", ex);
        Throwables.propagate(ex);
    }
    sourceCounter.start();
    super.start();
}

From source file:king.flow.test.net.EchoServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from  www.j  a  v a 2s. 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 {
                        //new LoggingHandler(LogLevel.INFO),
                        ch.pipeline().addLast(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:lunarion.cluster.coordinator.server.CoordinatorServer.java

License:Open Source License

public void bind(int port) throws InterruptedException {

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.RCVBUF_ALLOCATOR,
                    new AdaptiveRecvByteBufAllocator(64, 1024, 65536 * 512))
            //.childHandler(new ChildChannelHandler())
            .childHandler(new CoordinatorServerChannelInitializer(co, logger))
            .option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, true);

    Channel ch = bootstrap.bind(port).sync().channel();
    System.err//from  w ww. j  av  a2 s .c o m
            .println(Timer.currentTime() + "[INFO]: coordinator server channel binded at port: " + port + '.');
    logger.info(Timer.currentTime() + " [COORDINATOR INFO]:  coordinator server channel binded at port: " + port
            + '.');
    ch.closeFuture().sync();
    /*
     *  Bind and start to accept incoming connections.
     */
    // ChannelFuture future = bootstrap.bind(port).sync();
    /*
     *  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.
     */

    // future.channel().closeFuture().sync();

}

From source file:lunarion.node.LunarDBServerStandAlone.java

License:Open Source License

public void bind(int port) throws InterruptedException {

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.RCVBUF_ALLOCATOR,
                    new AdaptiveRecvByteBufAllocator(64, 1024, 65536 * 512))
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new LunarDBServerChannelInitializer(node_tc));

    Channel ch = bootstrap.bind(port).sync().channel();
    System.err.println(Timer.currentTime() + " DB node server channel binded at port: " + port + '.');
    logger.info(Timer.currentTime() + " [NODE INFO]:  DB node server channel binded at port: " + port + '.');
    ch.closeFuture().sync();//from   ww  w. j a  va2  s.com
    /*
     *  Bind and start to accept incoming connections.
     */
    // ChannelFuture future = bootstrap.bind(port).sync();
    /*
     *  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.
     */

    // future.channel().closeFuture().sync();

}

From source file:main.java.ch.epfl.lpd.ServerThread.java

License:Apache License

public void run() {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//  w  w  w  . j a v  a2  s  .c  o m
        SelfSignedCertificate ssc;
        try {
            ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("Got exception", e);
        }
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    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 ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        /*
                        if (sslCtx != null) {
                           p.addLast(sslCtx.newHandler(ch.alloc()));
                        }
                        */
                        p.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                        p.addLast("decoder", new StringDecoder());
                        p.addLast("encoder", new StringEncoder());
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new ServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f;
        try {
            f = b.bind(PORT).sync();
            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("Got exception", e);
        }

    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:majordodo.network.netty.NettyChannelAcceptor.java

License:Apache License

public void start() throws Exception {
    boolean useOpenSSL = NetworkUtils.isOpenSslAvailable();
    if (ssl) {/*from w w  w .  j  a  v  a  2  s .  co  m*/

        if (sslCertFile == null) {
            LOGGER.log(Level.SEVERE,
                    "start SSL with self-signed auto-generated certificate, useOpenSSL:" + useOpenSSL);
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            try {
                sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
                        .sslProvider(useOpenSSL ? SslProvider.OPENSSL : SslProvider.JDK).ciphers(sslCiphers)
                        .build();
            } finally {
                ssc.delete();
            }
        } else {
            LOGGER.log(Level.SEVERE, "start SSL with certificate " + sslCertFile.getAbsolutePath()
                    + " chain file " + sslCertChainFile.getAbsolutePath() + " , useOpenSSL:" + useOpenSSL);
            if (sslCiphers != null) {
                LOGGER.log(Level.SEVERE, "required sslCiphers " + sslCiphers);
            }
            sslCtx = SslContextBuilder.forServer(sslCertChainFile, sslCertFile, sslCertPassword)
                    .sslProvider(useOpenSSL ? SslProvider.OPENSSL : SslProvider.JDK).ciphers(sslCiphers)
                    .build();
        }

    }
    if (NetworkUtils.isEnableEpollNative()) {
        bossGroup = new EpollEventLoopGroup(workerThreads);
        workerGroup = new EpollEventLoopGroup(workerThreads);
        LOGGER.log(Level.INFO, "Using netty-native-epoll network type");
    } else {
        bossGroup = new NioEventLoopGroup(workerThreads);
        workerGroup = new NioEventLoopGroup(workerThreads);
    }
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(
            NetworkUtils.isEnableEpollNative() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    NettyChannel session = new NettyChannel("client", ch, callbackExecutor, null);
                    if (acceptor != null) {
                        acceptor.createConnection(session);
                    }

                    //                        ch.pipeline().addLast(new LoggingHandler());
                    // Add SSL handler first to encrypt and decrypt everything.
                    if (ssl) {
                        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
                    }

                    ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                    ch.pipeline().addLast("lengthbaseddecoder",
                            new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    //
                    ch.pipeline().addLast("messageencoder", new DodoMessageEncoder());
                    ch.pipeline().addLast("messagedecoder", new DodoMessageDecoder());
                    ch.pipeline().addLast(new InboundMessageHandler(session));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture f = b.bind(host, port).sync(); // (7)
    this.channel = f.channel();

}

From source file:me.ferrybig.p2pnetwork.Main.java

private void startIncomingConnectionThread(int port) {
    ServerBootstrap server = new ServerBootstrap();
    server.group(group);/*from  w w  w.  j av  a2 s .  co m*/
    server.channel(NioServerSocketChannel.class);
    server.option(ChannelOption.SO_BACKLOG, 128);
    server.childOption(ChannelOption.SO_KEEPALIVE, true);
    server.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            if (blocked.containsKey(((InetSocketAddress) ch.remoteAddress()).getAddress())) {
                LOG.info(ch + "Rejected at socket level");
                ch.close();
                return;
            }
            ch.pipeline().addLast(new LengthFieldPrepender(4));
            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new PacketEncoder());
            ch.pipeline().addLast(new PacketDecoder());
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new ServerBootstrapConnector(addr, incomingListener));
            clientsIn.add(ch);
            ch.closeFuture().addListener(e1 -> {
                clientsIn.remove(ch);
            });
        }
    });
    ChannelFuture f = server.bind(port);
    f.addListener(e -> {
        this.servers.add((ServerChannel) f.channel());
        f.channel().closeFuture().addListener(e1 -> {
            this.servers.remove((ServerChannel) f.channel());
        });
    });
}

From source file:me.ferrybig.p2pnetwork.Peer.java

public ChannelFuture startIncomingConnectionThread(int port) {
    ServerBootstrap server = new ServerBootstrap();
    server.group(group);/* w  w w.  java2  s  .  co m*/
    server.channel(NioServerSocketChannel.class);
    server.option(ChannelOption.SO_BACKLOG, 128);
    server.childOption(ChannelOption.SO_KEEPALIVE, true);
    server.childHandler(new ChannelConstructor(incomingListener, clientsIn));
    ChannelFuture f = server.bind(port);
    return f.addListener(e -> {
        if (e.isSuccess()) {
            this.servers.add((ServerChannel) f.channel());
            f.channel().closeFuture().addListener(e1 -> {
                this.servers.remove((ServerChannel) f.channel());
            });
        }
    });
}