Example usage for io.netty.channel ChannelOption SO_RCVBUF

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

Introduction

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

Prototype

ChannelOption SO_RCVBUF

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

Click Source Link

Usage

From source file:sas.systems.imflux.session.rtsp.SimpleRtspSession.java

License:Apache License

/**
 * {@inheritDoc}/*from  w ww  .j ava 2s.  c  o  m*/
 */
@Override
public synchronized boolean init() {
    if (this.running.get()) {
        return true;
    }

    // create bootstrap
    Class<? extends ServerChannel> channelType;
    if (useNio) {
        this.workerGroup = new NioEventLoopGroup();
        this.bossGroup = new NioEventLoopGroup();
        channelType = NioServerSocketChannel.class;
    } else {
        this.workerGroup = new OioEventLoopGroup();
        this.bossGroup = new OioEventLoopGroup();
        channelType = OioServerSocketChannel.class;
    }

    bootstrap = new ServerBootstrap();
    bootstrap.group(this.bossGroup, this.workerGroup).option(ChannelOption.SO_SNDBUF, this.sendBufferSize)
            .option(ChannelOption.SO_RCVBUF, this.receiveBufferSize).channel(channelType)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<Channel>() { // is used to initialize the ChannelPipeline
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("encoder", new RtspEncoder());
                    pipeline.addLast("decoder", new RtspDecoder());
                    pipeline.addLast("aggregator", new HttpObjectAggregator(64 * 1024));
                    pipeline.addLast("handler", new RtspHandler(SimpleRtspSession.this));
                }
            });
    // create channel
    try {
        ChannelFuture future = bootstrap.bind(this.localAddress);
        this.channel = future.sync().channel(); // wait for future to complete and retrieve channel

    } catch (Exception e) {
        LOG.error("Failed to bind RTSP channel for session with id " + this.id, e);
        this.workerGroup.shutdownGracefully();
        this.bossGroup.shutdownGracefully();

        this.workerGroup.terminationFuture().syncUninterruptibly();
        this.bossGroup.terminationFuture().syncUninterruptibly();
        return false;
    }
    LOG.debug("RTSP channel bound for RtspSession with id {}.", this.id);
    this.running.set(true);
    return true;
}

From source file:se.sics.gvod.net.NettyNetwork.java

License:Open Source License

/**
 * Start listening as a server at the given address..
 *
 * @param addr the address to listen at/*from  w  w  w .  java2  s.c om*/
 * @param port the port number to listen at
 * @param bindAllNetworkIfs whether to bind on all network interfaces
 * @return true if listening was started
 * @throws ChannelException in case binding failed
 */
private boolean bindUdpPort(final InetAddress addr, final int port, final boolean bindAllNetworkIfs) {

    if (udpPortsToSockets.containsKey(port)) {
        return true;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class)
            .handler(new NettyMsgHandler(component, Transport.UDP, msgDecoderClass));

    // Allow packets as large as up to 1600 bytes (default is 768).
    // You could increase or decrease this value to avoid truncated packets
    // or to improve memory footprint respectively.
    //
    // Please also note that a large UDP packet might be truncated or
    // dropped by your router no matter how you configured this option.
    // In UDP, a packet is truncated or dropped if it is larger than a
    // certain size, depending on router configuration. IPv4 routers
    // truncate and IPv6 routers drop a large packet. That's why it is
    // safe to send small packets in UDP.
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1500));
    bootstrap.option(ChannelOption.SO_RCVBUF, RECV_BUFFER_SIZE);

    bootstrap.option(ChannelOption.SO_SNDBUF, SEND_BUFFER_SIZE);
    // bootstrap.setOption("trafficClass", trafficClass);
    // bootstrap.setOption("soTimeout", soTimeout);
    // bootstrap.setOption("broadcast", broadcast);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);

    try {
        DatagramChannel c;
        if (bindAllNetworkIfs) {
            c = (DatagramChannel) bootstrap.bind(
                    //                        new InetSocketAddress(port)
                    port).sync().channel();
        } else {
            c = (DatagramChannel) bootstrap.bind(new InetSocketAddress(addr, port)).sync().channel();
        }

        addLocalSocket(new InetSocketAddress(addr, port), c);
        logger.debug("Successfully bound to ip:port {}:{}", addr, port);
    } catch (InterruptedException e) {
        logger.warn("Problem when trying to bind to {}:{}", addr.getHostAddress(), port);
        trigger(new Fault(e.getCause()), control);
        return false;
    }

    udpSocketsToBootstraps.put(new InetSocketAddress(addr, port), bootstrap);

    return true;
}

From source file:se.sics.kompics.network.netty.NettyNetwork.java

License:Open Source License

private boolean bindUdpPort(final InetAddress addr, final int port) {

    EventLoopGroup group = new NioEventLoopGroup();
    bootstrapUDP = new Bootstrap();
    bootstrapUDP.group(group).channel(NioDatagramChannel.class)
            .handler(new DatagramHandler(this, Transport.UDP));

    bootstrapUDP.option(ChannelOption.RCVBUF_ALLOCATOR,
            new AdaptiveRecvByteBufAllocator(1500, 1500, RECV_BUFFER_SIZE));
    bootstrapUDP.option(ChannelOption.SO_RCVBUF, RECV_BUFFER_SIZE);
    bootstrapUDP.option(ChannelOption.SO_SNDBUF, SEND_BUFFER_SIZE);
    // bootstrap.setOption("trafficClass", trafficClass);
    // bootstrap.setOption("soTimeout", soTimeout);
    // bootstrap.setOption("broadcast", broadcast);
    bootstrapUDP.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MS);
    bootstrapUDP.option(ChannelOption.SO_REUSEADDR, true);

    try {//w  w  w  .  j  a v  a2  s.c o m
        InetSocketAddress iAddr = new InetSocketAddress(addr, port);
        DatagramChannel c = (DatagramChannel) bootstrapUDP.bind(iAddr).sync().channel();

        addLocalSocket(iAddr, c);
        LOG.info("Successfully bound to ip:port {}:{}", addr, port);
    } catch (InterruptedException e) {
        LOG.error("Problem when trying to bind to {}:{}", addr.getHostAddress(), port);
        return false;
    }

    return true;
}

From source file:spark.network.netty.FileServer.java

License:Apache License

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

    // Configure the server.
    bootstrap = new ServerBootstrap();
    bootstrap.group(new OioEventLoopGroup(), new OioEventLoopGroup()).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 {/* w  w  w  .j a  v a 2s .  c  o  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:storage.netty.HTTPUploadClientAsync.java

License:Apache License

public void putBlob(String filepath) throws Exception {

    String resourceUrl = "/mycontainer/" + randomString(5);
    String putBlobUrl = base_url + resourceUrl;

    URI uriSimple = new URI(putBlobUrl);
    String scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme();
    String host = uriSimple.getHost() == null ? "127.0.0.1" : uriSimple.getHost();
    int port = uriSimple.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/* w ww  .ja va2  s  .  c o m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    File path = new File(filepath);
    if (!path.canRead()) {
        throw new FileNotFoundException(filepath);
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();

    // setup the factory: here using a mixed memory/disk based on size threshold
    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed

    DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskFileUpload.baseDirectory = null; // system temp directory
    DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskAttribute.baseDirectory = null; // system temp directory

    try {

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientInitializer(sslCtx));
        b.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 64 * 1024);
        b.option(ChannelOption.SO_SNDBUF, 1048576);
        b.option(ChannelOption.SO_RCVBUF, 1048576);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_REUSEADDR, true);
        b.option(ChannelOption.AUTO_CLOSE, true);

        //Iterate over files

        Collection<ChannelFuture> futures = new ArrayList<ChannelFuture>();

        for (final File file : path.listFiles()) {

            String blobname = file.getName();
            System.out.println(blobname);

            HttpRequest request = formpost(host, port, resourceUrl + blobname, file, factory);
            ChannelFuture cf = b.connect(host, port);
            futures.add(cf);
            cf.channel().attr(HTTPREQUEST).set(request);
            cf.channel().attr(FILETOUPLOAD).set(file);

            cf.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture future) throws Exception {

                    // check to see if we succeeded
                    if (future.isSuccess()) {
                        System.out.println("connected for " + blobname);
                    } else {
                        System.out.println(future.cause().getMessage());
                    }
                }
            });
        }

        for (ChannelFuture cf : futures) {
            cf.channel().closeFuture().awaitUninterruptibly();
        }

    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();

        // Really clean all temporary files if they still exist
        factory.cleanAllHttpDatas();
    }

}

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

License:Apache License

private ServerBootstrap createBootstrap() {
    final ServerBootstrap boot = createBootstrapOfType(
            mTachyonConf.getEnum(Constants.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) mTachyonConf.getBytes(Constants.WORKER_NETTY_WATERMARK_HIGH));
    boot.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK,
            (int) mTachyonConf.getBytes(Constants.WORKER_NETTY_WATERMARK_LOW));

    // more buffer settings on Netty socket option, one can tune them by specifying
    // properties, e.g.:
    // tachyon.worker.network.netty.backlog=50
    // tachyon.worker.network.netty.buffer.send=64KB
    // tachyon.worker.network.netty.buffer.receive=64KB
    if (mTachyonConf.containsKey(Constants.WORKER_NETTY_BACKLOG)) {
        boot.option(ChannelOption.SO_BACKLOG, mTachyonConf.getInt(Constants.WORKER_NETTY_BACKLOG));
    }/*from   w ww.  java2s  . co  m*/
    if (mTachyonConf.containsKey(Constants.WORKER_NETTY_SEND_BUFFER)) {
        boot.option(ChannelOption.SO_SNDBUF, (int) mTachyonConf.getBytes(Constants.WORKER_NETTY_SEND_BUFFER));
    }
    if (mTachyonConf.containsKey(Constants.WORKER_NETTY_RECEIVE_BUFFER)) {
        boot.option(ChannelOption.SO_RCVBUF,
                (int) mTachyonConf.getBytes(Constants.WORKER_NETTY_RECEIVE_BUFFER));
    }
    return boot;
}

From source file:tonivade.redis.RedisClient.java

License:Open Source License

public void start() {
    workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    initHandler = new RedisInitializerHandler(this);
    connectionHandler = new RedisConnectionHandler(this);

    bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_RCVBUF, BUFFER_SIZE).option(ChannelOption.SO_SNDBUF, BUFFER_SIZE)
            .option(ChannelOption.SO_KEEPALIVE, true).handler(initHandler);

    try {/*  w  w w  . j  a v  a  2 s  . c  o m*/
        connect();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:tonivade.redis.RedisServer.java

License:Open Source License

public void start() {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
    acceptHandler = new RedisInitializerHandler(this);
    connectionHandler = new RedisConnectionHandler(this);

    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(acceptHandler)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_RCVBUF, BUFFER_SIZE).option(ChannelOption.SO_SNDBUF, BUFFER_SIZE)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    future = bootstrap.bind(host, port);
    // Bind and start to accept incoming connections.
    future.syncUninterruptibly();//ww w . j ava  2  s.c  o  m

    LOGGER.info(() -> "server started: " + host + ":" + port);
}

From source file:weekend.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  .java2s  . c o  m
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    this.bootstrap.group(this.eventLoopGroup).channel(NioSocketChannel.class)//
            //
            .option(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_SNDBUF, NettySystemConfig.SocketSndbufSize)
            //
            .option(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize)
            //
            .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());
                }
            });

    // ?1??
    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();
    }
}