Example usage for io.netty.channel ChannelOption SO_SNDBUF

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

Introduction

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

Prototype

ChannelOption SO_SNDBUF

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

Click Source Link

Usage

From source file:NettyHttpListner.java

License:Apache License

public void start() {

    System.out.println("Starting the server...");
    System.out.println("Starting Inbound Http Listner on Port " + this.port);

    // Configure SSL.
    SslContext sslCtx = null;//www  .  ja  va 2  s  . c  o  m
    if (SSL) {
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (CertificateException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SSLException ex) {
            Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    commonEventLoopGroup = new NioEventLoopGroup(bossGroupSize);
    //        bossGroup = new NioEventLoopGroup(bossGroupSize);
    //        workerGroup = new NioEventLoopGroup(workerGroupSize);

    try {
        ServerBootstrap b = new ServerBootstrap();

        //            b.commonEventLoopGroup(bossGroup, workerGroup)
        b.group(commonEventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(
                        new NettyHttpTransportHandlerInitializer(HOST, HOST_PORT, maxConnectionsQueued, sslCtx))
                .childOption(ChannelOption.AUTO_READ, false);

        b.option(ChannelOption.TCP_NODELAY, true);
        b.childOption(ChannelOption.TCP_NODELAY, true);

        b.option(ChannelOption.SO_BACKLOG, maxConnectionsQueued);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

        b.option(ChannelOption.SO_SNDBUF, 1048576);
        b.option(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_RCVBUF, 1048576);
        b.childOption(ChannelOption.SO_SNDBUF, 1048576);

        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        Channel ch = null;
        try {
            ch = b.bind(port).sync().channel();
            ch.closeFuture().sync();
            System.out.println("Inbound Listner Started");
        } catch (InterruptedException e) {
            System.out.println("Exception caught");
        }
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * activating registered handler to accept events.
 *
 * @param ctx/* ww w  .jav a2s. co  m*/
 * @throws Exception
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass());
    b.handler(new NettyTargetHandlerInitilizer(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

    b.option(ChannelOption.SO_SNDBUF, 1048576);
    b.option(ChannelOption.SO_RCVBUF, 1048576);

    ChannelFuture f = b.connect(NettyHttpListner.HOST, NettyHttpListner.HOST_PORT);

    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });

}

From source file:alluxio.worker.netty.NettyDataServer.java

License:Apache License

private ServerBootstrap createBootstrap() {
    final ServerBootstrap boot = createBootstrapOfType(
            Configuration.getEnum(PropertyKey.WORKER_NETWORK_NETTY_CHANNEL, ChannelType.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,
            (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_WATERMARK_HIGH));
    boot.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK,
            (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_WATERMARK_LOW));

    // more buffer settings on Netty socket option, one can tune them by specifying
    // properties, e.g.:
    // alluxio.worker.network.netty.backlog=50
    // alluxio.worker.network.netty.buffer.send=64KB
    // alluxio.worker.network.netty.buffer.receive=64KB
    if (Configuration.containsKey(PropertyKey.WORKER_NETWORK_NETTY_BACKLOG)) {
        boot.option(ChannelOption.SO_BACKLOG, Configuration.getInt(PropertyKey.WORKER_NETWORK_NETTY_BACKLOG));
    }/*from   w  ww.j ava2s  .  c  o m*/
    if (Configuration.containsKey(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_SEND)) {
        boot.option(ChannelOption.SO_SNDBUF,
                (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_SEND));
    }
    if (Configuration.containsKey(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_RECEIVE)) {
        boot.option(ChannelOption.SO_RCVBUF,
                (int) Configuration.getBytes(PropertyKey.WORKER_NETWORK_NETTY_BUFFER_RECEIVE));
    }
    return boot;
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java

License:Apache License

/**
 * Tulio Ribeiro Connect to specific replica and returns the ChannelFuture.
 * sessionClientToReplica is replaced with the new connection. Removed redundant
 * code.//from w ww.  j a  v a  2s  .c o m
 */
public synchronized ChannelFuture connectToReplica(int replicaId, SecretKeyFactory fac)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {

    String str = this.clientId + ":" + replicaId;
    PBEKeySpec spec = TOMUtil.generateKeySpec(str.toCharArray());
    SecretKey authKey = fac.generateSecret(spec);

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec);
    b.handler(getChannelInitializer());

    ChannelFuture channelFuture = b.connect(controller.getRemoteAddress(replicaId));

    NettyClientServerSession ncss = new NettyClientServerSession(channelFuture.channel(), replicaId);
    sessionClientToReplica.put(replicaId, ncss);

    return channelFuture;
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemServerSide.java

License:Apache License

public NettyClientServerCommunicationSystemServerSide(ServerViewController controller) {
    try {//from w w  w  . j av  a 2s  . com

        this.controller = controller;
        /* Tulio Ribeiro */
        privKey = controller.getStaticConf().getPrivateKey();

        sessionReplicaToClient = new ConcurrentHashMap<>();
        rl = new ReentrantReadWriteLock();

        // Configure the server.

        serverPipelineFactory = new NettyServerPipelineFactory(this, sessionReplicaToClient, controller, rl);

        EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreads);
        EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, tcpSendBufferSize)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec)
                .option(ChannelOption.SO_BACKLOG, connectionBacklog)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(serverPipelineFactory.getDecoder());
                        ch.pipeline().addLast(serverPipelineFactory.getEncoder());
                        ch.pipeline().addLast(serverPipelineFactory.getHandler());
                    }
                }).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true);
        String myAddress;
        String confAddress = controller.getStaticConf()
                .getRemoteAddress(controller.getStaticConf().getProcessId()).getAddress().getHostAddress();

        if (InetAddress.getLoopbackAddress().getHostAddress().equals(confAddress)) {

            myAddress = InetAddress.getLoopbackAddress().getHostAddress();

        }

        else if (controller.getStaticConf().getBindAddress().equals("")) {

            myAddress = InetAddress.getLocalHost().getHostAddress();

            // If Netty binds to the loopback address, clients will not be able to connect
            // to replicas.
            // To solve that issue, we bind to the address supplied in config/hosts.config
            // instead.
            if (InetAddress.getLoopbackAddress().getHostAddress().equals(myAddress)
                    && !myAddress.equals(confAddress)) {

                myAddress = confAddress;
            }

        } else {

            myAddress = controller.getStaticConf().getBindAddress();
        }

        int myPort = controller.getStaticConf().getPort(controller.getStaticConf().getProcessId());

        ChannelFuture f = b.bind(new InetSocketAddress(myAddress, myPort)).sync();

        logger.info("ID = " + controller.getStaticConf().getProcessId());
        logger.info("N = " + controller.getCurrentViewN());
        logger.info("F = " + controller.getCurrentViewF());
        logger.info("Port (client <-> server) = "
                + controller.getStaticConf().getPort(controller.getStaticConf().getProcessId()));
        logger.info("Port (server <-> server) = "
                + controller.getStaticConf().getServerToServerPort(controller.getStaticConf().getProcessId()));
        logger.info("requestTimeout = " + controller.getStaticConf().getRequestTimeout());
        logger.info("maxBatch = " + controller.getStaticConf().getMaxBatchSize());
        if (controller.getStaticConf().getUseSignatures() == 1)
            logger.info("Using Signatures");
        else if (controller.getStaticConf().getUseSignatures() == 2)
            logger.info("Using benchmark signature verification");
        logger.info("Binded replica to IP address " + myAddress);
        // ******* EDUARDO END **************//

        /* Tulio Ribeiro */
        // SSL/TLS
        logger.info("SSL/TLS enabled, protocol version: {}",
                controller.getStaticConf().getSSLTLSProtocolVersion());

        /* Tulio Ribeiro END */

        mainChannel = f.channel();

    } catch (InterruptedException | UnknownHostException ex) {
        logger.error("Failed to create Netty communication system", ex);
    }
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyRemotingClient.java

License:Apache License

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

                private AtomicInteger threadIndex = new AtomicInteger(0);

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

    Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker);//
    if (isLinux) {
        handler.channel(EpollSocketChannel.class);
    } else {
        handler.channel(NioSocketChannel.class);
    }
    //
    handler.option(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_KEEPALIVE, false)
            //
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            //
            .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize())
            //
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(//
                            defaultEventExecutorGroup, //
                            new NettyEncoder(), //
                            new NettyDecoder(), //
                            new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), //
                            new NettyConnetManageHandler(), //
                            new NettyClientHandler());
                }
            });

    this.timer.scheduleAtFixedRate(new TimerTask() {

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

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

From source file:com.alibaba.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 .ja v a 2  s .  co  m
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker);
    if (isLinux) {
        childHandler.channel(EpollServerSocketChannel.class);
    } else {
        childHandler.channel(NioServerSocketChannel.class);
    }
    if (isLinux) {
        childHandler.option(EpollChannelOption.SO_REUSEPORT, true);
    }
    //
    childHandler.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.alibaba.rocketmq.remoting.netty.NettyUDPClient.java

License:Apache License

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

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//from   w w  w  .ja  va 2  s.  c om
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioDatagramChannel.class)//
            //
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            //
            .handler(new ChannelInitializer<DatagramChannel>() {
                @Override
                public void initChannel(DatagramChannel ch) throws Exception {
                    ch.pipeline().addLast(//
                            defaultEventExecutorGroup, //
                            new NettyEncoder(), //
                            new NettyDecoder(), //
                            //new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()),//
                            new NettyConnetManageHandler(), //
                            new NettyClientHandler());
                }
            });

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

From source file:com.alibaba.rocketmq.remoting.netty.NettyUDPServer.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  a va2  s. c  o m
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupWorker).channel(NioDatagramChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .option(ChannelOption.SO_KEEPALIVE, false)
                    //
                    .option(ChannelOption.SO_BROADCAST, true)
                    //
                    .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenUDPPort()))
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        public void initChannel(DatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new UDP2BufAdapt(), new NettyEncoder(), //
                                    //
                                    //new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),//
                                    //new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        // ????
        childHandler.option(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 {
                NettyUDPServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}

From source file:com.baidu.jprotobuf.pbrpc.transport.RpcClient.java

License:Apache License

public RpcClient(Class<? extends Channel> clientChannelClass, RpcClientOptions rpcClientOptions) {
    this.workerGroup = new NioEventLoopGroup();
    this.group(workerGroup);
    this.channel(clientChannelClass);
    this.handler(new RpcClientPipelineinitializer(this));
    this.rpcClientOptions = rpcClientOptions;
    this.option(ChannelOption.SO_REUSEADDR, rpcClientOptions.isReuseAddress());
    this.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, rpcClientOptions.getConnectTimeout());
    this.option(ChannelOption.SO_SNDBUF, rpcClientOptions.getSendBufferSize());
    this.option(ChannelOption.SO_RCVBUF, rpcClientOptions.getSendBufferSize());
    this.option(ChannelOption.SO_KEEPALIVE, rpcClientOptions.isKeepAlive());
    this.option(ChannelOption.TCP_NODELAY, rpcClientOptions.getTcpNoDelay());
    this.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR,
            new DefaultMessageSizeEstimator(rpcClientOptions.getReceiveBufferSize()));

    // add count/* w w  w . ja va 2s  .  com*/
    INSTANCE_COUNT.incrementAndGet();
}