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:org.apache.rocketmq.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//from   w  w w . j  av a  2 s. co  m
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = this.serverBootstrap
            .group(this.eventLoopGroupBoss, this.eventLoopGroupSelector).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();
    }

    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:org.apache.spark.network.netty.FileServer.java

License:Apache License

FileServer(PathResolver pResolver, int port) {
    InetSocketAddress addr = new InetSocketAddress(port);

    // Configure the server.
    bossGroup = new OioEventLoopGroup();
    workerGroup = new OioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(OioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption.SO_RCVBUF, 1500)
            .childHandler(new FileServerChannelInitializer(pResolver));
    // Start the server.
    channelFuture = bootstrap.bind(addr);
    try {//from  w  w w  .j  a v  a 2  s  .co  m
        // Get the address we bound to.
        InetSocketAddress boundAddress = ((InetSocketAddress) channelFuture.sync().channel().localAddress());
        this.port = boundAddress.getPort();
    } catch (InterruptedException ie) {
        this.port = 0;
    }
}

From source file:org.apache.spark.network.server.TransportServer.java

License:Apache License

private void init(String hostToBind, int portToBind) {

    IOMode ioMode = IOMode.valueOf(conf.ioMode());
    EventLoopGroup bossGroup = NettyUtils.createEventLoop(ioMode, conf.serverThreads(),
            conf.getModuleName() + "-server");
    EventLoopGroup workerGroup = bossGroup;

    PooledByteBufAllocator allocator = NettyUtils.createPooledByteBufAllocator(conf.preferDirectBufs(),
            true /* allowCache */, conf.serverThreads());

    bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
            .channel(NettyUtils.getServerChannelClass(ioMode)).option(ChannelOption.ALLOCATOR, allocator)
            .option(ChannelOption.SO_REUSEADDR, !SystemUtils.IS_OS_WINDOWS)
            .childOption(ChannelOption.ALLOCATOR, allocator);

    this.metrics = new NettyMemoryMetrics(allocator, conf.getModuleName() + "-server", conf);

    if (conf.backLog() > 0) {
        bootstrap.option(ChannelOption.SO_BACKLOG, conf.backLog());
    }//from w w  w  .j av  a2  s . c  o  m

    if (conf.receiveBuf() > 0) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, conf.receiveBuf());
    }

    if (conf.sendBuf() > 0) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, conf.sendBuf());
    }

    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) {
            RpcHandler rpcHandler = appRpcHandler;
            for (TransportServerBootstrap bootstrap : bootstraps) {
                rpcHandler = bootstrap.doBootstrap(ch, rpcHandler);
            }
            context.initializePipeline(ch, rpcHandler);
        }
    });

    InetSocketAddress address = hostToBind == null ? new InetSocketAddress(portToBind)
            : new InetSocketAddress(hostToBind, portToBind);
    channelFuture = bootstrap.bind(address);
    channelFuture.syncUninterruptibly();

    port = ((InetSocketAddress) channelFuture.channel().localAddress()).getPort();
    logger.debug("Shuffle server started on port: {}", port);
}

From source file:org.apache.spark.sql.hive.thriftserver.rsc.RpcServer.java

License:Apache License

public RpcServer(RSCConf lconf) throws IOException, InterruptedException {
    this.config = lconf;
    this.group = new NioEventLoopGroup(this.config.getInt(RSCConf.Entry.RPC_MAX_THREADS),
            Utils.newDaemonThreadFactory("RPC-Handler-%d"));
    this.channel = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from w w w  . j a  v  a 2 s . c o m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    SaslServerHandler saslHandler = new SaslServerHandler(config);
                    final Rpc newRpc = Rpc.createServer(saslHandler, config, ch, group);
                    saslHandler.rpc = newRpc;

                    Runnable cancelTask = new Runnable() {
                        @Override
                        public void run() {
                            LOG.warn("Timed out waiting for hello from client.");
                            newRpc.close();
                        }
                    };
                    saslHandler.cancelTask = group.schedule(cancelTask,
                            config.getTimeAsMs(RSCConf.Entry.RPC_CLIENT_HANDSHAKE_TIMEOUT),
                            TimeUnit.MILLISECONDS);
                }
            }).option(ChannelOption.SO_BACKLOG, 1).option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true).bind(0).sync().channel();
    this.port = ((InetSocketAddress) channel.localAddress()).getPort();
    this.pendingClients = new ConcurrentHashMap<>();

    String address = config.get(RSCConf.Entry.RPC_SERVER_ADDRESS);
    if (address == null) {
        address = config.findLocalAddress();
    }
    this.address = address;
}

From source file:org.artJava.upload.file.server.FileServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO//from w w  w  . ja  va  2s.co 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 ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                        ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                        ch.pipeline().addLast(new FileServerHandler());
                    }
                });

        // ???
        ChannelFuture f = b.bind(port).sync();

        // ???
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.asterisque.netty.Netty.java

License:Apache License

/**
 * ??????????/* w  w  w.j  a  v  a  2  s. com*/
 *
 * @return Server ? Future
 */
public CompletableFuture<Server> newServer(Node node, SocketAddress address, Options options,
        Consumer<Wire> onAccept) {
    NioEventLoopGroup master = new NioEventLoopGroup(); // ??????
    ServerBootstrap server = new ServerBootstrap();
    CompletableFuture<Server> future = new CompletableFuture<>();

    Initializer factory = new Initializer(node, true, options, wire -> {
        logger.debug(Asterisque.logPrefix(true) + ": onAccept(" + wire + ")");
        onAccept.accept(wire);
    });

    server.group(master, worker()).channel(NioServerSocketChannel.class).localAddress(address)
            .option(ChannelOption.SO_BACKLOG, options.get(Options.KEY_SERVER_BACKLOG).get())
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE).childHandler(factory);

    server.bind().addListener(f -> {
        if (f.isSuccess()) {
            logger.info(Asterisque.logPrefix(true) + ": startup server: " + Debug.toString(address));
            future.complete(new Server(node, address, options) {
                @Override
                public void close() {
                    master.shutdownGracefully();
                }
            });
        } else {
            logger.error(Asterisque.logPrefix(true) + ": server bind failure: " + Debug.toString(address),
                    f.cause());
            future.completeExceptionally(f.cause());
            master.shutdownGracefully();
        }
    });
    return future;
}

From source file:org.ballerinalang.test.agent.server.WebServer.java

License:Open Source License

/**
 * Initializes the server, socket, and channel.
 *
 * @param loopGroup The event loop group.
 * @param serverChannelClass The socket channel class.
 * @throws InterruptedException on interruption.
 *///from  w  w  w .  j av a2  s .com
private void start(final EventLoopGroup loopGroup, final Class<? extends ServerChannel> serverChannelClass)
        throws InterruptedException {
    try {
        final InetSocketAddress inet = new InetSocketAddress(host, port);

        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        serverBootstrap.option(ChannelOption.SO_REUSEADDR, true);
        serverBootstrap.group(loopGroup).channel(serverChannelClass).childHandler(new WebServerInitializer());
        serverBootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);
        serverBootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
        serverBootstrap.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE);

        final Channel ch = serverBootstrap.bind(inet).sync().channel();
        ch.closeFuture().sync();
    } finally {
        loopGroup.shutdownGracefully().sync();
    }
}

From source file:org.caffinitas.prometheusmetrics.PrometheusMetricsExporter.java

License:Apache License

private void setupNetty() throws CertificateException, SSLException {
    final SslContext sslCtx;
    if (config.ssl) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        LOGGER.info("Setting up SSL context for certificate subject DN {} valid until {}",
                ssc.cert().getSubjectDN(), ssc.cert().getNotAfter());
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {/*from w  w w . ja v a 2s. co m*/
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    this.nettyChannel = new ServerBootstrap().option(ChannelOption.SO_BACKLOG, 1024)
            .group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ServerInitializer(sslCtx)).bind(config.bindAddress, config.httpPort)
            .syncUninterruptibly().channel();

    nettyChannel.closeFuture().addListener(f -> {
        LOGGER.info("Shutting down listener");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    });
}

From source file:org.cane.rpc.server.NettyRpcServer.java

License:Open Source License

@Override
public void start() {
    bossGroup = new NioEventLoopGroup();
    workGroup = new NioEventLoopGroup();
    try {/*w ww .  j  a  v a 2s . c o  m*/
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline().addLast();
            }
        });
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        String[] hostAndPort = serverAddress.split(":");

        ChannelFuture future = serverBootstrap.bind(hostAndPort[0], Integer.parseInt(hostAndPort[1])).sync();

        if (serviceRegistry != null) {
            serviceRegistry.registerServer(serverAddress);
        }

        future.channel().closeFuture().sync();
    } catch (Exception e) {
        LOG.error("Init rpc server error!", e);
    }
}

From source file:org.eclipse.californium.elements.tcp.TcpServerConnector.java

License:Open Source License

@Override
public synchronized void start() throws IOException {
    if (rawDataChannel == null) {
        throw new IllegalStateException("Cannot start without message handler.");
    }/*from   ww  w .  j  a v  a 2  s .c  om*/
    if (bossGroup != null) {
        throw new IllegalStateException("Connector already started");
    }
    if (workerGroup != null) {
        throw new IllegalStateException("Connector already started");
    }

    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup(numberOfThreads);

    ServerBootstrap bootstrap = new ServerBootstrap();
    // server socket 
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelRegistry()).option(ChannelOption.SO_BACKLOG, 100)
            .option(ChannelOption.AUTO_READ, true).childOption(ChannelOption.SO_KEEPALIVE, true);

    // Start the server.
    ChannelFuture channelFuture = bootstrap.bind(localAddress).syncUninterruptibly();

    if (channelFuture.isSuccess() && 0 == localAddress.getPort()) {
        // replace port with the assigned one
        InetSocketAddress listenAddress = (InetSocketAddress) channelFuture.channel().localAddress();
        effectiveLocalAddress = new InetSocketAddress(localAddress.getAddress(), listenAddress.getPort());
    }
}