Example usage for io.netty.channel ChannelOption WRITE_BUFFER_HIGH_WATER_MARK

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

Introduction

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

Prototype

ChannelOption WRITE_BUFFER_HIGH_WATER_MARK

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

Click Source Link

Usage

From source file:com.netty.HttpHelloWorldServer.java

License:Apache License

public void start(String[] args) throws Exception {

    initSpringContext(args);/*from  www .j  a  v  a 2s .c o m*/
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1000);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                //                    .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpHelloWorldServerInitializer(applicationContext, sslCtx));
        b.option(ChannelOption.SO_BACKLOG, 128); // (5)
        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        b.childOption(ChannelOption.SO_KEEPALIVE, true);
        b.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
        b.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

        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.onion.worker.WorkerDataServer.java

License:Apache License

private ServerBootstrap createServerBootstrap() {
    final ServerBootstrap boot = new ServerBootstrap();
    // If number of worker threads is 0, Netty creates (#processors * 2) threads by default.
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup(0);
    boot.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);

    // use pooled buffers
    boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // set write buffer
    // this is the default, but its recommended to set it in case of change in future netty.
    boot.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32768);
    boot.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8192);

    return boot;/*  w w w  .j  ava  2s .c  o  m*/
}

From source file:com.Server.java

License:Apache License

/**
 * This is passive mode server//from  ww w .  j  a v  a  2 s  .  co  m
 * @param fs FTP Session Handler
 * @param host Server IP address
 * @param port Passive port no.
 */
public Server(String host, int port, int mode, String fileName) {
    InetSocketAddress inSocketAddress = new InetSocketAddress(host, port);
    try {
        ServerBootstrap bootStrap = new ServerBootstrap();
        bootStrap.group(bossGroup, workerGroup);
        bootStrap.channel(NioServerSocketChannel.class);
        bootStrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1);
        bootStrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1);
        bootStrap.childHandler(new MyChannelInitializer(this, mode, fileName));
        bootStrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        bootStrap.bind(inSocketAddress);
        System.out.println("Server started");
    } catch (Exception eg) {
        eg.printStackTrace();
        stop();
    }
}

From source file:com.whizzosoftware.hobson.api.plugin.channel.AbstractChannelObjectPlugin.java

License:Open Source License

private Bootstrap configureBootstrap(Bootstrap b) {
    b.group(connectionEventLoopGroup);/*from w  w w. j av  a2s.c o m*/
    b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
    b.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

    // configure for either network or serial channel
    if (isNetworkAddress()) {
        b.channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                channel.config().setConnectTimeoutMillis(5000);
                configureChannel(channel.config());
                configurePipeline(channel.pipeline());
            }
        });
    } else {
        b.channel(RxtxChannel.class);
        b.handler(new ChannelInitializer<RxtxChannel>() {
            @Override
            public void initChannel(RxtxChannel channel) throws Exception {
                configureChannel(channel.config());
                configurePipeline(channel.pipeline());
            }
        });
    }

    return b;
}

From source file:eu.stratosphere.runtime.io.network.netty.NettyConnectionManager.java

License:Apache License

public NettyConnectionManager(ChannelManager channelManager, InetAddress bindAddress, int bindPort,
        int bufferSize, int numInThreads, int numOutThreads, int lowWaterMark, int highWaterMark) {
    this.outConnections = new ConcurrentHashMap<RemoteReceiver, Object>();
    this.channelManager = channelManager;

    // --------------------------------------------------------------------

    int defaultNumThreads = Math.max(Runtime.getRuntime().availableProcessors() / 4, 1);
    numInThreads = (numInThreads == -1) ? defaultNumThreads : numInThreads;
    numOutThreads = (numOutThreads == -1) ? defaultNumThreads : numOutThreads;
    LOG.info(String.format("Starting with %d incoming and %d outgoing connection threads.", numInThreads,
            numOutThreads));/*from w w  w.ja  v a  2 s  . c om*/

    lowWaterMark = (lowWaterMark == -1) ? bufferSize / 2 : lowWaterMark;
    highWaterMark = (highWaterMark == -1) ? bufferSize : highWaterMark;
    LOG.info(String.format("Setting low water mark to %d and high water mark to %d bytes.", lowWaterMark,
            highWaterMark));

    // --------------------------------------------------------------------
    // server bootstrap (incoming connections)
    // --------------------------------------------------------------------
    this.in = new ServerBootstrap();
    this.in.group(new NioEventLoopGroup(numInThreads)).channel(NioServerSocketChannel.class)
            .localAddress(bindAddress, bindPort).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline()
                            .addLast(new InboundEnvelopeDecoder(NettyConnectionManager.this.channelManager))
                            .addLast(new InboundEnvelopeDispatcherHandler(
                                    NettyConnectionManager.this.channelManager));
                }
            }).option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(bufferSize))
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // --------------------------------------------------------------------
    // client bootstrap (outgoing connections)
    // --------------------------------------------------------------------
    this.out = new Bootstrap();
    this.out.group(new NioEventLoopGroup(numOutThreads)).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new OutboundEnvelopeEncoder());
                }
            }).option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, lowWaterMark)
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, highWaterMark)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY, false).option(ChannelOption.SO_KEEPALIVE, true);

    try {
        this.in.bind().sync();
    } catch (InterruptedException e) {
        throw new RuntimeException("Could not bind server socket for incoming connections.");
    }

    if (LOG.isDebugEnabled()) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Date date = new Date();

                while (true) {
                    try {
                        Thread.sleep(DEBUG_PRINT_QUEUED_ENVELOPES_EVERY_MS);

                        date.setTime(System.currentTimeMillis());
                        System.out.println(date);

                        System.out.println(getNonZeroNumQueuedEnvelopes());

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

From source file:io.lettuce.core.AbstractRedisClient.java

License:Apache License

/**
 * Populate connection builder with necessary resources.
 *
 * @param socketAddressSupplier address supplier for initial connect and re-connect
 * @param connectionBuilder connection builder to configure the connection
 * @param redisURI URI of the Redis instance
 *///from   w w  w.j a  v a  2 s .c om
protected void connectionBuilder(Mono<SocketAddress> socketAddressSupplier, ConnectionBuilder connectionBuilder,
        RedisURI redisURI) {

    Bootstrap redisBootstrap = new Bootstrap();
    redisBootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
    redisBootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    redisBootstrap.option(ChannelOption.ALLOCATOR, BUF_ALLOCATOR);

    SocketOptions socketOptions = getOptions().getSocketOptions();

    redisBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
            Math.toIntExact(socketOptions.getConnectTimeout().toMillis()));

    if (LettuceStrings.isEmpty(redisURI.getSocket())) {
        redisBootstrap.option(ChannelOption.SO_KEEPALIVE, socketOptions.isKeepAlive());
        redisBootstrap.option(ChannelOption.TCP_NODELAY, socketOptions.isTcpNoDelay());
    }

    connectionBuilder.timeout(redisURI.getTimeout());
    connectionBuilder.password(redisURI.getPassword());

    connectionBuilder.bootstrap(redisBootstrap);
    connectionBuilder.channelGroup(channels).connectionEvents(connectionEvents).timer(timer);
    connectionBuilder.socketAddressSupplier(socketAddressSupplier);
}

From source file:io.maelstorm.server.ServerInit.java

License:Open Source License

public void start(String configFile, RequestHandler handler) throws Exception {
    LOG.info("Starting.");
    AppendableCharSequenceAddon.configure();
    try {//w ww  .  ja  va  2 s.  c  o m
        System.in.close(); // Release a FD we don't need.
    } catch (Exception e) {
        LOG.warn("Failed to close stdin", e);
    }
    Properties prop = getProperties(configFile);
    requestDistributor = handler;
    requestDistributor.setInitializer(this);
    String os = System.getProperty("os.name").toLowerCase(Locale.UK).trim();
    if (os.startsWith("linux")) {
        bossGroup = (null == bossGroup) ? new EpollEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new EpollEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    } else {
        bossGroup = (null == bossGroup) ? new NioEventLoopGroup(1) : bossGroup;
        workerGroup = (null == workerGroup) ? new NioEventLoopGroup(NUM_WORKER_THREADS) : workerGroup;
    }

    String[] servers = prop.getProperty("servers").split(",");
    for (String server : servers) {

        try {
            controller = new ServerBootstrap();
            controller.group(bossGroup, workerGroup);
            if (os.startsWith("linux")) {
                controller.channel(EpollServerSocketChannel.class);
                controller.option(EpollChannelOption.TCP_CORK, true);
            } else {
                controller.channel(NioServerSocketChannel.class);
            }
            controller.childHandler(new PipelineFactory(handler, getPipelineConfig(prop, server)));
            controller.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
            controller.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                    getInt(prop, server, "connectTimeoutMillis"));
            controller.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 1 * 1024);
            controller.option(ChannelOption.SO_KEEPALIVE, getBoolean(prop, server, "SOKeepalive"));
            controller.option(ChannelOption.SO_REUSEADDR, true);
            controller.option(ChannelOption.TCP_NODELAY, true);
            controller.option(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            controller.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024);
            controller.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10);
            controller.childOption(ChannelOption.SO_KEEPALIVE, true);
            controller.childOption(ChannelOption.SO_REUSEADDR, true);
            controller.childOption(ChannelOption.TCP_NODELAY, true);
            controller.childOption(ChannelOption.SO_LINGER, 0);
            controller.childOption(ChannelOption.SO_RCVBUF, 6291456);

            final InetSocketAddress addr = new InetSocketAddress(getInt(prop, server, "port"));
            ChannelFuture future = controller.bind(addr).sync();
            if (future.isSuccess())
                LOG.info("Server Ready to serve on " + addr);
            else
                throw new Exception("Address already in use");
        } catch (Throwable t) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            throw new RuntimeException("Initialization failed", t);
        }
    }
}

From source file:org.anhonesteffort.chnlbrkr.ChnlBrkrServer.java

License:Open Source License

public void run() throws InterruptedException {
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    IdleChnlzrConnectionFactory idleFactory = new IdleChnlzrConnectionFactory(config);
    IdleChnlzrController idleController = new IdleChnlzrController(idleFactory);
    ChannelStreamerFactory streamFactory = new ChannelStreamerFactory(config);

    Optional<RedisClient> redisClient = (redisUri.isPresent()) ? Optional.of(RedisClient.create(redisUri.get()))
            : Optional.<RedisClient>empty();

    BrkrList brkrList = new BrkrList(config, hostId, workerGroup, redisClient);
    Optional<ChnlzrIdPubSub> chnlzrPubSub = (redisClient.isPresent())
            ? Optional.of(new ChnlzrIdPubSub(config, redisClient.get(), idleController))
            : Optional.empty();/*from  w w w .j ava 2  s .  c  o m*/

    try {

        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, config.bufferHighWaterMark())
                .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, config.bufferLowWaterMark())
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast("idle state", new IdleStateHandler(0, 0,
                                config.idleStateThresholdMs(), TimeUnit.MILLISECONDS));
                        ch.pipeline().addLast("heartbeat", IdleStateHeartbeatWriter.INSTANCE);
                        ch.pipeline().addLast("encoder", BaseMessageEncoder.INSTANCE);
                        ch.pipeline().addLast("decoder", new BaseMessageDecoder());
                        ch.pipeline().addLast("brkrlist", brkrList);
                        ch.pipeline().addLast("handler",
                                new ServerHandler(config, idleController, streamFactory, chnlzrPubSub));
                    }
                });

        ChannelFuture channelFuture = bootstrap.bind(listenPort).sync();
        channelFuture.channel().closeFuture().sync();

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        if (redisClient.isPresent()) {
            redisClient.get().shutdown();
        }
    }
}

From source file:org.anhonesteffort.chnlzr.ChnlzrServer.java

License:Open Source License

@SuppressWarnings("unchecked")
private void run() throws InterruptedException {
    ListenableFuture sourceFuture = sourcePool.submit(source);
    Futures.addCallback(sourceFuture, criticalCallback);

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    try {/*from  w  w  w.  j  a  v  a  2  s . c om*/

        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, config.bufferHighWaterMark())
                .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, config.bufferLowWaterMark())
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast("idle state", new IdleStateHandler(0, 0,
                                config.idleStateThresholdMs(), TimeUnit.MILLISECONDS));
                        ch.pipeline().addLast("heartbeat", IdleStateHeartbeatWriter.INSTANCE);
                        ch.pipeline().addLast("encoder", BaseMessageEncoder.INSTANCE);
                        ch.pipeline().addLast("decoder", new BaseMessageDecoder());
                        ch.pipeline().addLast("handler",
                                new ServerHandler(config, resampling, sourceController));
                    }
                });

        ChannelFuture channelFuture = bootstrap.bind(config.serverPort()).sync();
        channelFuture.channel().closeFuture().sync();

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        sourceFuture.cancel(true);
        sourcePool.shutdownNow();
    }

    System.exit(1);
}

From source file:org.anhonesteffort.p25.chnlzr.ChnlzrConnectionFactory.java

License:Open Source License

public ListenableFuture<ChnlzrConnectionHandler> create(HostId chnlzrHost) {
    SettableFuture<ChnlzrConnectionHandler> future = SettableFuture.create();
    ChnlzrConnectionHandler connection = new ChnlzrConnectionHandler(future);
    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(workerGroup).channel(channel).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectionTimeoutMs())
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, config.bufferHighWaterMark())
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, config.bufferLowWaterMark())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from w w w  .ja v  a2 s .  co m*/
                public void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast("idle state",
                            new IdleStateHandler(0, 0, config.idleStateThresholdMs(), TimeUnit.MILLISECONDS));
                    ch.pipeline().addLast("heartbeat", IdleStateHeartbeatWriter.INSTANCE);
                    ch.pipeline().addLast("encoder", BaseMessageEncoder.INSTANCE);
                    ch.pipeline().addLast("decoder", new BaseMessageDecoder());
                    ch.pipeline().addLast("connector", connection);
                }
            });

    bootstrap.connect(chnlzrHost.getHostname(), chnlzrHost.getPort()).addListener(connect -> {
        if (!connect.isSuccess())
            future.setException(new ConnectException("failed to connect to chnlzr"));
    });

    return future;
}