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:io.vertx.core.net.impl.transport.Transport.java

License:Open Source License

public void configure(NetServerOptions options, ServerBootstrap bootstrap) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }//from  w  w w  .j a  v  a2  s. c o m
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.childOption(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.childOption(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
    if (options.getAcceptBacklog() != -1) {
        bootstrap.option(ChannelOption.SO_BACKLOG, options.getAcceptBacklog());
    }
}

From source file:jj.http.server.HttpServer.java

License:Apache License

private void makeServerBootstrap(int bindingCount) {
    serverBootstrap = new ServerBootstrap()
            .group(new NioEventLoopGroup(bindingCount, threadFactory), ioEventLoopGroup)
            .channel(NioServerSocketChannel.class).childHandler(initializer)
            .option(ChannelOption.SO_KEEPALIVE, configuration.keepAlive())
            .option(ChannelOption.SO_REUSEADDR, configuration.reuseAddress())
            .option(ChannelOption.TCP_NODELAY, configuration.tcpNoDelay())
            .option(ChannelOption.SO_TIMEOUT, configuration.timeout())
            .option(ChannelOption.SO_BACKLOG, configuration.backlog())
            .option(ChannelOption.SO_RCVBUF, configuration.receiveBufferSize())
            .option(ChannelOption.SO_SNDBUF, configuration.sendBufferSize());
}

From source file:lunarion.node.requester.LunarDBClient.java

License:Open Source License

public ChannelFuture connect(String host, int port) throws Exception {
    group = new NioEventLoopGroup();
    client_handler = new ClientHandler(internal);

    try {//from   ww  w.  j  a v  a2s  . c o m
        Bootstrap client_bootstrap = new Bootstrap();
        client_bootstrap.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.SO_SNDBUF, 1024 * 1024)
                .option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 1024, 65536 * 512))
                //.option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true).handler(new ClientChannelInitializer(client_handler));

        //ChannelFuture cf = client_bootstrap.connect(host, port).sync();
        ChannelFuture cf = client_bootstrap.connect(host, port);
        channel_list.add(cf);

        cf.addListener(new ChannelFutureListener() {
            public void operationComplete(final ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    ClientHandler handler = channelFuture.channel().pipeline().get(ClientHandler.class);
                    client_handler = handler;

                }
            }
        });

        connected.set(true);
        connected_host_ip = host;
        connected_port = port;

        return cf;
    } finally {

        // group.shutdownGracefully();
    }
}

From source file:net.kuujo.copycat.netty.NettyTcpProtocolClient.java

License:Apache License

@Override
public CompletableFuture<Void> connect() {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    if (channel != null) {
        future.complete(null);// w  ww . jav a  2s .c om
        return future;
    }

    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {
            sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
        } catch (SSLException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    group = new NioEventLoopGroup(protocol.getThreads());
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslContext != null) {
                pipeline.addLast(sslContext.newHandler(channel.alloc(), host, port));
            }
            pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
            pipeline.addLast("bytesDecoder", new ByteArrayDecoder());
            pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
            pipeline.addLast("bytesEncoder", new ByteArrayEncoder());
            pipeline.addLast("handler", channelHandler);
        }
    });

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_LINGER, protocol.getSoLinger());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, protocol.getConnectTimeout());

    bootstrap.connect(host, port).addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            channel = channelFuture.channel();
            future.complete(null);
        } else {
            future.completeExceptionally(channelFuture.cause());
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.NettyTcpProtocolServer.java

License:Apache License

@Override
public synchronized CompletableFuture<Void> listen() {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {/*from  w w  w. j  av  a  2s .  c o  m*/
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (SSLException | CertificateException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    serverGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup(protocol.getThreads());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast(sslContext.newHandler(channel.alloc()));
                    }
                    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
                    pipeline.addLast("bytesDecoder", new ByteArrayDecoder());
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.addLast("bytesEncoder", new ByteArrayEncoder());
                    pipeline.addLast("handler", new ServerHandler());
                }
            }).option(ChannelOption.SO_BACKLOG, 128);

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog());

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(host, port).addListener((ChannelFutureListener) channelFuture -> {
        channelFuture.channel().closeFuture().addListener(closeFuture -> {
            workerGroup.shutdownGracefully();
        });

        if (channelFuture.isSuccess()) {
            channel = channelFuture.channel();
            future.complete(null);
        } else {
            future.completeExceptionally(channelFuture.cause());
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolClient.java

License:Apache License

@Override
public CompletableFuture<Void> connect() {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    if (channel != null) {
        future.complete(null);//from   w  w w.  j  av a 2 s . c o  m
        return future;
    }

    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {
            sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
        } catch (SSLException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    final EventLoopGroup group = new NioEventLoopGroup(protocol.getThreads());
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslContext != null) {
                pipeline.addLast(
                        sslContext.newHandler(channel.alloc(), protocol.getHost(), protocol.getPort()));
            }
            pipeline.addLast(new ObjectEncoder(),
                    new ObjectDecoder(
                            ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())),
                    new TcpProtocolClientHandler(TcpProtocolClient.this));
        }
    });

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay());
    bootstrap.option(ChannelOption.SO_LINGER, protocol.getSoLinger());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, protocol.getConnectTimeout());

    bootstrap.connect(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                channel = channelFuture.channel();
                future.complete(null);
            } else {
                future.completeExceptionally(channelFuture.cause());
            }
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java

License:Apache License

@Override
public CompletableFuture<Void> start() {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    // TODO: Configure proper SSL trust store.
    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {/*from w  ww  . jav a  2s . c  om*/
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (SSLException | CertificateException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    final EventLoopGroup serverGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup(protocol.getThreads());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast(sslContext.newHandler(channel.alloc()));
                    }
                    pipeline.addLast(new ObjectEncoder(),
                            new ObjectDecoder(
                                    ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())),
                            new TcpProtocolServerHandler(TcpProtocolServer.this));
                }
            }).option(ChannelOption.SO_BACKLOG, 128);

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay());
    bootstrap.option(ChannelOption.SO_REUSEADDR, protocol.isReuseAddress());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive());
    bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog());

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    workerGroup.shutdownGracefully();
                }
            });

            if (channelFuture.isSuccess()) {
                channel = channelFuture.channel();
                future.complete(null);
            } else {
                future.completeExceptionally(channelFuture.cause());
            }
        }
    });
    return future;
}

From source file:net.marfgamer.jraknet.util.RakNetUtils.java

License:Open Source License

/**
 * Sends a raw message to the specified address for the specified amount of
 * times in the specified interval until the packet is received or there is
 * a timeout.//from  w w  w. ja v  a  2s . c  o  m
 * 
 * @param address
 *            the address to send the packet to.
 * @param packet
 *            the packet to send.
 * @param timeout
 *            the interval of which the packet is sent.
 * @param retries
 *            how many times the packet will be sent.
 * @return the received packet if it was received.
 */
private static RakNetPacket createBootstrapAndSend(InetSocketAddress address, Packet packet, long timeout,
        int retries) {
    RakNetPacket packetReceived = null;

    // Create bootstrap and bind
    EventLoopGroup group = new NioEventLoopGroup();

    try {
        Bootstrap bootstrap = new Bootstrap();
        BootstrapHandler handler = new BootstrapHandler();
        bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_RCVBUF, RakNet.MINIMUM_TRANSFER_UNIT)
                .option(ChannelOption.SO_SNDBUF, RakNet.MINIMUM_TRANSFER_UNIT).handler(handler);

        // Create channel, send packet, and close it
        Channel channel = bootstrap.bind(0).sync().channel();
        channel.writeAndFlush(new DatagramPacket(packet.buffer(), address));

        // Wait for packet to come in, return null on timeout
        while (retries > 0) {
            long sendTime = System.currentTimeMillis();
            while (System.currentTimeMillis() - sendTime < timeout) {
                if (handler.packet != null) {
                    packetReceived = handler.packet;
                    break; // We found the packet
                }
            }
            if (packetReceived != null) {
                break; // the master loop is no longer needed
            }
            retries--;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // Shutdown bootstrap
    group.shutdownGracefully();
    return packetReceived;
}

From source file:net.NettyEngine4.ServerServiceImpl.java

License:Apache License

/**
 *  run netty server/*from w  w  w . ja va2  s .c  om*/
 *  NioEventLoopGroup used for NIO Selector based Channels
 *  two NioEventLoopGroup(AioEventLoopGroup) will be used. The first is
 *  used to handle the accept of new connections and the second will serve the IO of them.
 *  IoEventLoopGroupThread +1;
 *  DefaultEventExecutorGroup ?
 *
 *  bossExecutor:?SocketChannel
 *  workerExecutorSocketChannel?channel/
 *  executionLogicHandlerThread????
 *  AIO ?channelgroup?group?
 *  option() is for the NioServerSocketChannel that accepts incoming connections
 *  childOption() is for the Channels accepted by the parent ServerChannel,
 *  which is NioServerSocketChannel in this case.
 *
 *   ServerBootstrap ?? parent channel
 *   parent channel ? connections
 *  ? connection ? child channel ??
 */
@Override
public void run() throws Exception {
    NioEventLoopGroup EventLoopGroupLister = new NioEventLoopGroup(0x1,
            new PriorityThreadFactory("@+main_reactor+@", Thread.NORM_PRIORITY));
    NioEventLoopGroup IOEventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() + 1,
            new PriorityThreadFactory("@+sub_reactor+@", Thread.NORM_PRIORITY));
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    try {
        serverBootstrap.group(EventLoopGroupLister, IOEventLoopGroup).channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_REUSEADDR, true) //??
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false))// heap buf 's better
                .childOption(ChannelOption.SO_RCVBUF, 1048576).childOption(ChannelOption.SO_SNDBUF, 1048576)
                .childHandler(new ServerChannelInitializer());//used to serve the request for the {@link Channel}'s
        // Bind and start to accept incoming connections.
        ChannelFuture channelFuture = serverBootstrap
                .bind(new InetSocketAddress(Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort)).sync();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("server??:" + Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort);
        // Wait until the server socket is closed.
        // In this server, this does not happen, but you can do that to gracefully
        // shut down your server.
        channelFuture.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        EventLoopGroupLister.shutdownGracefully();
        IOEventLoopGroup.shutdownGracefully();
    }
}

From source file:net.NettyEngine4.ServerServiceImpl.java

License:Apache License

/**
 * jni native Epoll/* www.java 2s .  co  m*/
 #NioEventLoopGroup  EpollEventLoopGroup   ---- EventLoopGroup ?
 #NioEventLoop  EpollEventLoop
 #NioServerSocketChannel  EpollServerSocketChannel
 #NioSocketChannel  EpollSocketChannel        ---- SocketChannel?
        
 ## RHEL/CentOS/Fedora:
 #sudo yum install autoconf automake libtool glibc-devel.i686 glibc-devel libgcc.i686 make
 ## Debian/Ubuntu:
 #sudo apt-get install autoconf automake libtool make gcc-multilib
 * @throws Exception
 */
@Override
public void runNativeEpoll() throws Exception {
    EpollEventLoopGroup BossEventLoopGroup = new EpollEventLoopGroup(0x1,
            new PriorityThreadFactory("@+?", Thread.NORM_PRIORITY)); //mainReactor    1
    EpollEventLoopGroup WorkerEventLoopGroup = new EpollEventLoopGroup(
            Runtime.getRuntime().availableProcessors() + 0x1,
            new PriorityThreadFactory("@+I/O", Thread.NORM_PRIORITY)); //subReactor       ?cpu+1
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    try {
        serverBootstrap.group(BossEventLoopGroup, WorkerEventLoopGroup).channel(EpollServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_REUSEADDR, true) //??
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false))// heap buf 's better
                .childOption(ChannelOption.SO_RCVBUF, 1048576).childOption(ChannelOption.SO_SNDBUF, 1048576)
                .childHandler(new ServerChannelInitializer());//used to serve the request for the {@link Channel}'s
        // Bind and start to accept incoming connections.
        ChannelFuture channelFuture = serverBootstrap
                .bind(new InetSocketAddress(Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort)).sync();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("server??:" + Config.DEFAULT_VALUE.SERVER_VALUE.gameserverPort);
        // Wait until the server socket is closed.
        // In this server, this does not happen, but you can do that to gracefully
        // shut down your server.
        channelFuture.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        BossEventLoopGroup.shutdownGracefully();
        WorkerEventLoopGroup.shutdownGracefully();
    }
}