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.dinstone.jrpc.transport.netty5.NettyAcceptance.java

License:Apache License

@Override
public Acceptance bind() {
    bossGroup = new NioEventLoopGroup(1, new DefaultExecutorServiceFactory("N5A-Boss"));
    workGroup = new NioEventLoopGroup(transportConfig.getNioProcessorCount(),
            new DefaultExecutorServiceFactory("N5A-Work"));

    ServerBootstrap boot = new ServerBootstrap();
    boot.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/*w  w  w . j a  v  a2  s.c om*/
                public void initChannel(SocketChannel ch) throws Exception {
                    TransportProtocolDecoder decoder = new TransportProtocolDecoder();
                    decoder.setMaxObjectSize(transportConfig.getMaxSize());
                    TransportProtocolEncoder encoder = new TransportProtocolEncoder();
                    encoder.setMaxObjectSize(transportConfig.getMaxSize());
                    ch.pipeline().addLast("TransportProtocolDecoder", decoder);
                    ch.pipeline().addLast("TransportProtocolEncoder", encoder);

                    int intervalSeconds = transportConfig.getHeartbeatIntervalSeconds();
                    ch.pipeline().addLast("IdleStateHandler", new IdleStateHandler(intervalSeconds * 2, 0, 0));
                    ch.pipeline().addLast("NettyServerHandler", new NettyServerHandler());
                }
            });
    boot.option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_BACKLOG, 128);
    boot.childOption(ChannelOption.SO_RCVBUF, 16 * 1024).childOption(ChannelOption.SO_SNDBUF, 16 * 1024)
            .childOption(ChannelOption.TCP_NODELAY, true);

    try {
        boot.bind(serviceAddress).sync();

        int processorCount = transportConfig.getBusinessProcessorCount();
        if (processorCount > 0) {
            NamedThreadFactory threadFactory = new NamedThreadFactory("N5A-BusinssProcessor");
            executorService = Executors.newFixedThreadPool(processorCount, threadFactory);
        }
    } catch (Exception e) {
        throw new RuntimeException("can't bind service on " + serviceAddress, e);
    }
    LOG.info("netty5 acceptance bind on {}", serviceAddress);

    return this;
}

From source file:com.dinstone.rpc.netty.server.NettyServer.java

License:Apache License

public void start() {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {/*from   w w  w . ja va2  s  . c o  m*/
        ServerBootstrap boot = new ServerBootstrap();
        boot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new RpcProtocolDecoder(true));
                        ch.pipeline().addLast(new RpcProtocolEncoder(true));
                        ch.pipeline().addLast(new NettyServerHandler(handler));
                    }
                });
        boot.option(ChannelOption.SO_BACKLOG, 128);
        boot.childOption(ChannelOption.SO_KEEPALIVE, true);

        int port = config.getInt(Constants.SERVICE_PORT, Constants.DEFAULT_SERVICE_PORT);
        InetSocketAddress localAddress = new InetSocketAddress(port);
        String host = config.get(Constants.SERVICE_HOST);
        if (host != null) {
            localAddress = new InetSocketAddress(host, port);
        }
        LOG.info("RPC service works on " + localAddress);

        boot.bind(localAddress).sync();
    } catch (InterruptedException e) {
        throw new RpcException(500, "Server can't bind to the specified local address ", e);
    }
}

From source file:com.diwayou.hybrid.remoting.netty.NettyRemotingServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override// ww  w .  ja va 2s  .  co m
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker)
                    .channel(NioServerSocketChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .option(ChannelOption.SO_KEEPALIVE, false)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new NettyEncoder(), //
                                    new NettyDecoder(), //
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                                    new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        // ????
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}

From source file:com.dlc.server.DLCHttpServer.java

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  w  ww .j a  v a  2  s . c om
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    // 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 DLCHttpServerInitializer(sslCtx));

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

        System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:"
                + PORT + '/');

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

From source file:com.doctor.netty5.ebook.netty_the_definitive_guide.Chapter4ForTimerServer.java

License:Apache License

public void bind(int port) throws InterruptedException {
    // ??NIO//w w w .  j ava2  s.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, 1024).childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new TimeServerHander());

                    }
                });

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

From source file:com.doctor.netty5.ebook.netty_the_definitive_guide.TimeServer.java

License:Apache License

public void bind(int port) throws InterruptedException {
    // ??NIO/*w w  w  . jav  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, 1024).childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeServerHander());

                    }
                });

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

From source file:com.doctor.netty5.example.http.helloworld.HelloWorldServer.java

License:Apache License

public void start() throws InterruptedException {
    ServerBootstrap bootstrap = new ServerBootstrap();
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*  w ww.ja v a  2  s .  c  om*/
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(port)
                .option(ChannelOption.SO_BACKLOG, 1024).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec());
                        ch.pipeline().addLast(new HelloWorldServerHandler());
                    }
                });

        ChannelFuture channelFuture = bootstrap.bind().sync();
        System.out.println(HelloWorldServer.class.getName() + " started and listen on port:"
                + channelFuture.channel().localAddress());

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

From source file:com.ebay.jetstream.http.netty.server.Acceptor.java

License:MIT License

/**
 * @param rxSessionHandler/*from ww  w .  j a  v a  2s.  c o  m*/
 * @throws Exception
 */
public void bind(final HttpRequestHandler httpReqHandler, final HttpServerStatisticsHandler statisticsHandler)
        throws Exception {
    m_bossGroup = new NioEventLoopGroup(1, new NameableThreadFactory("NettyHttpServerAcceptor"));
    m_workerGroup = new NioEventLoopGroup(m_numIoProcessors,
            new NameableThreadFactory("NettyHttpServerWorker"));

    try {
        m_serverbootstrap = new ServerBootstrap();
        m_serverbootstrap.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("timeout", new IdleStateHandler((int) m_readIdleTimeout, 0, 0));
                        ch.pipeline().addLast("stats", statisticsHandler);
                        ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                        ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                        ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                        ch.pipeline().addLast("deflater", new HttpContentCompressor(1));
                        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(m_maxContentLength));
                        if (m_maxKeepAliveRequests > 0 || m_maxKeepAliveTimeout > 0) {
                            ch.pipeline().addLast("keepAliveHandler",
                                    new KeepAliveHandler(m_maxKeepAliveRequests, m_maxKeepAliveTimeout));
                        }
                        ch.pipeline().addLast("handler", httpReqHandler);

                    }

                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.SO_KEEPALIVE, false);

        if (m_config.getRvcBufSz() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_RCVBUF, (int) m_config.getRvcBufSz());
        }

        if (m_config.getSendBufSz() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_SNDBUF, (int) m_config.getSendBufSz());
        }

    } catch (Exception t) {
        throw t;
    }

    m_acceptorSocket = new InetSocketAddress(m_ipAddress, m_tcpPort);
    m_serverbootstrap.bind(m_acceptorSocket).sync();

    if (!m_ipAddress.isLoopbackAddress() && !m_ipAddress.isAnyLocalAddress()) {
        // Add lookback if not bind
        m_localAcceptorSocket = new InetSocketAddress("127.0.0.1", m_tcpPort);
        m_serverbootstrap.bind(m_localAcceptorSocket).sync();
    }
}

From source file:com.ebay.jetstream.messaging.transport.netty.eventconsumer.Acceptor.java

License:MIT License

/**
 * @param rxSessionHandler/*  w  w  w  .ja  v a  2 s .  co m*/
 * @throws Exception
 */
public void bind(EventProducerSessionHandler rxSessionHandler) throws Exception {

    m_rxSessionHandler = rxSessionHandler;
    m_bossGroup = new NioEventLoopGroup(1,
            new NameableThreadFactory("NettyAcceptor-" + m_tc.getTransportName()));
    m_workerGroup = new NioEventLoopGroup(m_numIoProcessors,
            new NameableThreadFactory("NettyReceiver-" + m_tc.getTransportName()));

    try {
        m_serverbootstrap = new ServerBootstrap();
        m_serverbootstrap.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addFirst("msghandler", m_rxSessionHandler);

                        StreamMessageDecoder decoder = new StreamMessageDecoder(
                                ClassResolvers.weakCachingConcurrentResolver(null));
                        ch.pipeline().addBefore("msghandler", "msgdecoder", decoder);
                        ch.pipeline().addBefore("msgdecoder", "kryoEcnoder", new KryoObjectEncoder());
                        ch.pipeline().addBefore("kryoEcnoder", "msgencoder", new NettyObjectEncoder());

                        if (m_enableCompression) {

                            ch.pipeline().addBefore("msgencoder", "decompressor",
                                    new MessageDecompressionHandler(false, 250000));

                            ch.pipeline().addBefore("decompressor", "idleTimeoutHandler",
                                    new IdleStateHandler((int) m_readIdleTimeout, 0, 0));
                        } else
                            ch.pipeline().addBefore("msgencoder", "idleTimeoutHandler",
                                    new IdleStateHandler((int) m_readIdleTimeout, 0, 0));

                    }
                }).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .childOption(ChannelOption.SO_KEEPALIVE, isTcpKeepAlive());

        if (m_tc.getReceivebuffersize() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_RCVBUF, m_tc.getReceivebuffersize());
        }

        if (m_tc.getSendbuffersize() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_SNDBUF, m_tc.getSendbuffersize());
        }

    } catch (Exception t) {
        throw t;
    }

    // we are given a port from DNS. We will check if it is taken. If it is
    // we will increment the port # by 10 and keep trying 10 times.
    // adding this feature so that we can operate the cluster on a single
    // node. Very useful for debugging and also for demos.

    int retryCount = 20;
    int port = m_tcpPort;

    while (retryCount-- > 0) {
        if (isPortAvailable(port))
            break;
        port += 1;

    }

    if (retryCount == 0)
        return; // we did not find a port to bind

    m_tcpPort = port;

    LOGGER.info("Acceptor bound to port" + m_tcpPort);

}

From source file:com.example.discard.DiscardServerMain.java

License:Apache License

public void run() throws Exception {
    final NioEventLoopGroup bossGroup = new NioEventLoopGroup();//1
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    try (AutoCloseable ignore = new ShutDownGracefully(bossGroup, workerGroup)) {
        final ServerBootstrap bootstrap = new ServerBootstrap();//2
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)//3
                .childHandler(new ChannelInitializer<SocketChannel>() {//4
                    @Override/* w  w w.  j  a  va2s.c o m*/
                    protected void initChannel(final SocketChannel ch) {
                        ch.pipeline().addLast(new DiscardServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128)//5
                .childOption(ChannelOption.SO_KEEPALIVE, true); //6
        final ChannelFuture channelFuture = bootstrap.bind(port).sync();//7
        channelFuture.channel().closeFuture().sync();
    }
}