Example usage for io.netty.channel ChannelOption WRITE_SPIN_COUNT

List of usage examples for io.netty.channel ChannelOption WRITE_SPIN_COUNT

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption WRITE_SPIN_COUNT.

Prototype

ChannelOption WRITE_SPIN_COUNT

To view the source code for io.netty.channel ChannelOption WRITE_SPIN_COUNT.

Click Source Link

Usage

From source file:com.heliosapm.streams.onramp.OnRampBoot.java

License:Apache License

/**
 * Creates a new OnRampBoot/*w w  w.  ja  va2 s. c  o m*/
 * @param appConfig  The application configuration
 */
public OnRampBoot(final Properties appConfig) {
    final String jmxmpUri = ConfigurationHelper.getSystemThenEnvProperty("jmx.jmxmp.uri",
            "jmxmp://0.0.0.0:1893", appConfig);
    JMXHelper.fireUpJMXMPServer(jmxmpUri);
    MessageForwarder.initialize(appConfig);
    port = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.port", 8091, appConfig);
    bindInterface = ConfigurationHelper.getSystemThenEnvProperty("onramp.network.bind", "0.0.0.0", appConfig);
    bindSocket = new InetSocketAddress(bindInterface, port);
    workerThreads = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.worker_threads", CORES * 2,
            appConfig);
    connectTimeout = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.sotimeout", 0, appConfig);
    backlog = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.backlog", 3072, appConfig);
    writeSpins = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.writespins", 16, appConfig);
    recvBuffer = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.recbuffer", 43690, appConfig);
    sendBuffer = ConfigurationHelper.getIntSystemThenEnvProperty("onramp.network.sendbuffer", 8192, appConfig);
    disableEpoll = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.epoll.disable", false,
            appConfig);
    async = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.async_io", true, appConfig);
    tcpNoDelay = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.tcp_no_delay", true,
            appConfig);
    keepAlive = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.keep_alive", true,
            appConfig);
    reuseAddress = ConfigurationHelper.getBooleanSystemThenEnvProperty("onramp.network.reuse_address", true,
            appConfig);
    tcpPipelineFactory = new PipelineFactory(appConfig);
    udpPipelineFactory = new UDPPipelineFactory();
    tcpServerBootstrap.handler(new LoggingHandler(getClass(), LogLevel.INFO));
    tcpServerBootstrap.childHandler(tcpPipelineFactory);
    // Set the child options
    tcpServerBootstrap.childOption(ChannelOption.ALLOCATOR, BufferManager.getInstance().getAllocator());
    tcpServerBootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    tcpServerBootstrap.childOption(ChannelOption.SO_KEEPALIVE, keepAlive);
    tcpServerBootstrap.childOption(ChannelOption.SO_RCVBUF, recvBuffer);
    tcpServerBootstrap.childOption(ChannelOption.SO_SNDBUF, sendBuffer);
    tcpServerBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, writeSpins);
    // Set the server options
    tcpServerBootstrap.option(ChannelOption.SO_BACKLOG, backlog);
    tcpServerBootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    tcpServerBootstrap.option(ChannelOption.SO_RCVBUF, recvBuffer);
    tcpServerBootstrap.option(ChannelOption.SO_TIMEOUT, connectTimeout);

    final StringBuilder tcpUri = new StringBuilder("tcp");
    final StringBuilder udpUri = new StringBuilder("udp");
    if (IS_LINUX && !disableEpoll) {
        bossExecutorThreadFactory = new ExecutorThreadFactory("EpollServerBoss", true);
        bossGroup = new EpollEventLoopGroup(1, (ThreadFactory) bossExecutorThreadFactory);
        workerExecutorThreadFactory = new ExecutorThreadFactory("EpollServerWorker", true);
        workerGroup = new EpollEventLoopGroup(workerThreads, (ThreadFactory) workerExecutorThreadFactory);
        tcpChannelType = EpollServerSocketChannel.class;
        udpChannelType = EpollDatagramChannel.class;
        tcpUri.append("epoll");
        udpUri.append("epoll");
    } else {
        bossExecutorThreadFactory = new ExecutorThreadFactory("NioServerBoss", true);
        bossGroup = new NioEventLoopGroup(1, bossExecutorThreadFactory);
        workerExecutorThreadFactory = new ExecutorThreadFactory("NioServerWorker", true);
        workerGroup = new NioEventLoopGroup(workerThreads, workerExecutorThreadFactory);
        tcpChannelType = NioServerSocketChannel.class;
        udpChannelType = NioDatagramChannel.class;
        tcpUri.append("nio");
        udpUri.append("nio");
    }

    tcpUri.append("://").append(bindInterface).append(":").append(port);
    udpUri.append("://").append(bindInterface).append(":").append(port);
    URI u = null;
    try {
        u = new URI(tcpUri.toString());
    } catch (URISyntaxException e) {
        log.warn("Failed TCP server URI const: [{}]. Programmer Error", tcpUri, e);
    }
    tcpServerURI = u;
    try {
        u = new URI(udpUri.toString());
    } catch (URISyntaxException e) {
        log.warn("Failed UDP server URI const: [{}]. Programmer Error", udpUri, e);
    }
    udpServerURI = u;

    log.info(">>>>> Starting OnRamp TCP Listener on [{}]...", tcpServerURI);
    log.info(">>>>> Starting OnRamp UDP Listener on [{}]...", udpServerURI);
    final ChannelFuture cf = tcpServerBootstrap.channel(tcpChannelType).group(bossGroup, workerGroup)
            .bind(bindSocket).awaitUninterruptibly()
            .addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(final Future<? super Void> f) throws Exception {
                    log.info("<<<<< OnRamp TCP Listener on [{}] Started", tcpServerURI);
                };
            }).awaitUninterruptibly();
    final ChannelFuture ucf = udpBootstrap.channel(udpChannelType).group(workerGroup)
            .option(ChannelOption.SO_BROADCAST, true).handler(new UDPPipelineFactory()).bind(bindSocket)
            .awaitUninterruptibly().addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(final Future<? super Void> f) throws Exception {
                    log.info("<<<<< OnRamp UDP Listener on [{}] Started", udpServerURI);
                };
            }).awaitUninterruptibly();

    tcpServerChannel = cf.channel();
    udpServerChannel = ucf.channel();
    tcpCloseFuture = tcpServerChannel.closeFuture();
    udpCloseFuture = udpServerChannel.closeFuture();
    Runtime.getRuntime().addShutdownHook(shutdownHook);

}

From source file:jlibs.wamp4j.netty.NettyClientEndpoint.java

License:Apache License

@Override
public void connect(final URI uri, final ConnectListener listener, final String... subProtocols) {
    final SslContext sslContext;
    if ("wss".equals(uri.getScheme())) {
        try {/*  ww w.j a  v a 2  s .c  om*/
            if (sslSettings == null) {
                sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
                        .build();
            } else {
                sslContext = SslContextBuilder.forClient().trustManager(sslSettings.trustCertChainFile)
                        .keyManager(sslSettings.certificateFile, sslSettings.keyFile, sslSettings.keyPassword)
                        .build();
            }
        } catch (Throwable thr) {
            listener.onError(thr);
            return;
        }
    } else if ("ws".equals(uri.getScheme()))
        sslContext = null;
    else
        throw new IllegalArgumentException("invalid protocol: " + uri.getScheme());

    final int port = uri.getPort() == -1 ? (sslContext == null ? 80 : 443) : uri.getPort();

    Bootstrap bootstrap = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.MAX_MESSAGES_PER_READ, 50000).option(ChannelOption.WRITE_SPIN_COUNT, 50000)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    if (sslContext != null)
                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
                    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
                            WebSocketVersion.V13, Util.toString(subProtocols), false, new DefaultHttpHeaders());
                    ch.pipeline().addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                            new WebSocketClientProtocolHandler(handshaker) {
                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                        throws Exception {
                                    super.exceptionCaught(ctx, cause);
                                    listener.onError(cause);
                                }
                            }, new HandshakeListener(handshaker, listener));
                }
            });
    bootstrap.connect(uri.getHost(), port).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                assert !future.channel().isOpen();
                listener.onError(future.cause());
            }
        }
    });
}

From source file:jlibs.wamp4j.netty.NettyServerEndpoint.java

License:Apache License

@Override
public void bind(final URI uri, final String subProtocols[], final AcceptListener listener) {
    final SslContext sslContext;
    if ("wss".equals(uri.getScheme())) {
        try {/*from  w w  w . j  a v a 2  s . co  m*/
            if (sslSettings == null) {
                SelfSignedCertificate ssc = new SelfSignedCertificate();
                sslSettings = new SSLSettings().keyFile(ssc.privateKey()).certificateFile(ssc.certificate());
            }
            ClientAuth clientAuth = ClientAuth.values()[sslSettings.clientAuthentication.ordinal()];
            sslContext = SslContextBuilder
                    .forServer(sslSettings.certificateFile, sslSettings.keyFile, sslSettings.keyPassword)
                    .clientAuth(clientAuth).trustManager(sslSettings.trustCertChainFile).build();
        } catch (Throwable thr) {
            listener.onError(thr);
            return;
        }
    } else if ("ws".equals(uri.getScheme()))
        sslContext = null;
    else
        throw new IllegalArgumentException("invalid protocol: " + uri.getScheme());

    int port = uri.getPort();
    if (port == -1)
        port = sslContext == null ? 80 : 443;
    ServerBootstrap bootstrap = new ServerBootstrap().group(eventLoopGroup)
            .channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.MAX_MESSAGES_PER_READ, 50000)
            .childOption(ChannelOption.WRITE_SPIN_COUNT, 50000)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    if (sslContext != null)
                        ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                    ch.pipeline().addLast(new HttpServerCodec(), new HttpObjectAggregator(65536),
                            new Handshaker(uri, listener, subProtocols));
                }
            });
    bootstrap.bind(uri.getHost(), port).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                channel.attr(ACCEPT_LISTENER).set(listener);
                listener.onBind(NettyServerEndpoint.this);
            } else
                listener.onError(future.cause());
        }
    });
}

From source file:org.opendaylight.ocpjava.protocol.impl.core.TcpHandler.java

License:Open Source License

/**
 * Starts server on selected port.//from ww  w.  ja va2  s  .c o  m
 */
@Override
public void run() {
    /*
     * We generally do not perform IO-unrelated tasks, so we want to have
     * all outstanding tasks completed before the executing thread goes
     * back into select.
     *
     * Any other setting means netty will measure the time it spent selecting
     * and spend roughly proportional time executing tasks.
     */
    workerGroup.setIoRatio(100);

    final ChannelFuture f;
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(channelInitializer)
                .option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true)
                //modify to "false" for OCP health-check
                .childOption(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, DEFAULT_WRITE_HIGH_WATERMARK * 1024)
                .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, DEFAULT_WRITE_LOW_WATERMARK * 1024)
                .childOption(ChannelOption.WRITE_SPIN_COUNT, DEFAULT_WRITE_SPIN_COUNT);

        if (startupAddress != null) {
            f = b.bind(startupAddress.getHostAddress(), port).sync();
        } else {
            f = b.bind(port).sync();
        }
    } catch (InterruptedException e) {
        LOG.error("Interrupted while binding port {}", port, e);
        return;
    }

    try {
        InetSocketAddress isa = (InetSocketAddress) f.channel().localAddress();
        address = isa.getHostString();

        // Update port, as it may have been specified as 0
        this.port = isa.getPort();

        LOG.debug("address from tcphandler: {}", address);
        isOnlineFuture.set(true);
        LOG.info("RadioHead listener started and ready to accept incoming tcp/tls connections on port: {}",
                port);
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for port {} shutdown", port, e);
    } finally {
        shutdown();
    }
}

From source file:ratpack.server.internal.DefaultRatpackServer.java

License:Apache License

protected Channel buildChannel(final ServerConfig serverConfig, final ChannelHandler handlerAdapter)
        throws InterruptedException {

    SslContext sslContext = serverConfig.getNettySslContext();
    this.useSsl = sslContext != null;

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverConfig.getConnectTimeoutMillis().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
        serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
    });//  ww  w  . j  av  a2  s  . c o m
    serverConfig.getMaxMessagesPerRead().ifPresent(i -> {
        FixedRecvByteBufAllocator allocator = new FixedRecvByteBufAllocator(i);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, allocator);
        serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, allocator);
    });
    serverConfig.getReceiveBufferSize().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.SO_RCVBUF, i);
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, i);
    });
    serverConfig.getWriteSpinCount().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.WRITE_SPIN_COUNT, i);
        serverBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, i);
    });
    serverConfig.getConnectQueueSize().ifPresent(i -> serverBootstrap.option(ChannelOption.SO_BACKLOG, i));

    return serverBootstrap.group(execController.getEventLoopGroup())
            .channel(ChannelImplDetector.getServerSocketChannelImpl())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    new ConnectionIdleTimeout(pipeline, serverConfig.getIdleTimeout());

                    if (sslContext != null) {
                        SSLEngine sslEngine = sslContext.newEngine(PooledByteBufAllocator.DEFAULT);
                        pipeline.addLast("ssl", new SslHandler(sslEngine));
                    }

                    pipeline.addLast("decoder", new HttpRequestDecoder(serverConfig.getMaxInitialLineLength(),
                            serverConfig.getMaxHeaderSize(), serverConfig.getMaxChunkSize(), false));
                    pipeline.addLast("encoder", new HttpResponseEncoder());
                    pipeline.addLast("deflater", new IgnorableHttpContentCompressor());
                    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
                    pipeline.addLast("adapter", handlerAdapter);

                    ch.config().setAutoRead(false);
                }
            }).bind(buildSocketAddress(serverConfig)).sync().channel();
}