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:dorkbox.network.Client.java

License:Apache License

/**
 * Starts a REMOTE <b>only</b> client, which will connect to the specified host using the specified Connections Options
 *//*from   ww  w  .jav  a 2 s. c  om*/
@SuppressWarnings("AutoBoxing")
public Client(final Configuration config) throws SecurityException {
    super(config);

    String threadName = Client.class.getSimpleName();

    this.config = config;
    boolean hostConfigured = (config.tcpPort > 0 || config.udpPort > 0) && config.host != null;
    boolean isLocalChannel = config.localChannelName != null;

    if (isLocalChannel && hostConfigured) {
        String msg = threadName
                + " Local channel use and TCP/UDP use are MUTUALLY exclusive. Unable to determine what to do.";
        logger.error(msg);
        throw new IllegalArgumentException(msg);
    }

    localChannelName = config.localChannelName;
    hostName = config.host;

    Bootstrap localBootstrap = null;
    Bootstrap tcpBootstrap = null;
    Bootstrap udpBootstrap = null;

    if (config.localChannelName != null) {
        localBootstrap = new Bootstrap();
    }

    if (config.tcpPort > 0 || config.udpPort > 0) {
        if (config.host == null) {
            throw new IllegalArgumentException("You must define what host you want to connect to.");
        }

        if (config.host.equals("0.0.0.0")) {
            throw new IllegalArgumentException(
                    "You cannot connect to 0.0.0.0, you must define what host you want to connect to.");
        }
    }

    if (config.tcpPort > 0) {
        tcpBootstrap = new Bootstrap();
    }

    if (config.udpPort > 0) {
        udpBootstrap = new Bootstrap();
    }

    if (localBootstrap == null && tcpBootstrap == null && udpBootstrap == null) {
        throw new IllegalArgumentException(
                "You must define how you want to connect, either LOCAL channel name, TCP port, or UDP port");
    }

    if (config.localChannelName != null) {
        // no networked bootstraps. LOCAL connection only

        bootstraps.add(new BootstrapWrapper("LOCAL", config.localChannelName, -1, localBootstrap));

        localBootstrap.group(newEventLoop(LOCAL, 1, threadName + "-JVM-BOSS")).channel(LocalChannel.class)
                .remoteAddress(new LocalAddress(config.localChannelName))
                .handler(new RegistrationLocalHandlerClient(threadName, registrationWrapper));
    }

    EventLoopGroup workerEventLoop = null;
    if (tcpBootstrap != null || udpBootstrap != null) {
        workerEventLoop = newEventLoop(config.workerThreadPoolSize, threadName);
    }

    if (tcpBootstrap != null) {
        bootstraps.add(new BootstrapWrapper("TCP", config.host, config.tcpPort, tcpBootstrap));

        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            tcpBootstrap.channel(OioSocketChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            tcpBootstrap.channel(EpollSocketChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            tcpBootstrap.channel(KQueueSocketChannel.class);
        } else {
            tcpBootstrap.channel(NioSocketChannel.class);
        }

        tcpBootstrap.group(newEventLoop(1, threadName + "-TCP-BOSS"))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))
                .remoteAddress(config.host, config.tcpPort).handler(new RegistrationRemoteHandlerClientTCP(
                        threadName, registrationWrapper, workerEventLoop));

        // android screws up on this!!
        tcpBootstrap.option(ChannelOption.TCP_NODELAY, !OS.isAndroid()).option(ChannelOption.SO_KEEPALIVE,
                true);
    }

    if (udpBootstrap != null) {
        bootstraps.add(new BootstrapWrapper("UDP", config.host, config.udpPort, udpBootstrap));

        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            udpBootstrap.channel(OioDatagramChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            udpBootstrap.channel(EpollDatagramChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            udpBootstrap.channel(KQueueDatagramChannel.class);
        } else {
            udpBootstrap.channel(NioDatagramChannel.class);
        }

        udpBootstrap.group(newEventLoop(1, threadName + "-UDP-BOSS"))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                // Netty4 has a default of 2048 bytes as upper limit for datagram packets.
                .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(EndPoint.udpMaxSize))
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))
                .localAddress(new InetSocketAddress(0)) // bind to wildcard
                .remoteAddress(new InetSocketAddress(config.host, config.udpPort))
                .handler(new RegistrationRemoteHandlerClientUDP(threadName, registrationWrapper,
                        workerEventLoop));

        // Enable to READ and WRITE MULTICAST data (ie, 192.168.1.0)
        // in order to WRITE: write as normal, just make sure it ends in .255
        // in order to LISTEN:
        //    InetAddress group = InetAddress.getByName("203.0.113.0");
        //    NioDatagramChannel.joinGroup(group);
        // THEN once done
        //    NioDatagramChannel.leaveGroup(group), close the socket
        udpBootstrap.option(ChannelOption.SO_BROADCAST, false).option(ChannelOption.SO_SNDBUF, udpMaxSize);
    }
}

From source file:dorkbox.network.Server.java

License:Apache License

/**
 * Convenience method to starts a server with the specified Connection Options
 */// www .ja  va  2 s. c  o  m
@SuppressWarnings("AutoBoxing")
public Server(Configuration config) throws SecurityException {
    // watch-out for serialization... it can be NULL incoming. The EndPoint (superclass) sets it, if null, so
    // you have to make sure to use this.serialization
    super(config);

    tcpPort = config.tcpPort;
    udpPort = config.udpPort;

    localChannelName = config.localChannelName;

    if (config.host == null) {
        // we set this to "0.0.0.0" so that it is clear that we are trying to bind to that address.
        hostName = "0.0.0.0";

        // make it clear that this is what we do (configuration wise) so that variable examination is consistent
        config.host = hostName;
    } else {
        hostName = config.host;
    }

    if (localChannelName != null) {
        localBootstrap = new ServerBootstrap();
    } else {
        localBootstrap = null;
    }

    if (tcpPort > 0) {
        tcpBootstrap = new ServerBootstrap();
    } else {
        tcpBootstrap = null;
    }

    if (udpPort > 0) {
        // This is what allows us to have UDP behave "similar" to TCP, in that a session is established based on the port/ip of the
        // remote connection. This allows us to reuse channels and have "state" for a UDP connection that normally wouldn't exist.
        // Additionally, this is what responds to discovery broadcast packets
        udpBootstrap = new SessionBootstrap(tcpPort, udpPort);
    } else {
        udpBootstrap = null;
    }

    String threadName = Server.class.getSimpleName();

    // always use local channels on the server.
    if (localBootstrap != null) {
        localBootstrap
                .group(newEventLoop(LOCAL, 1, threadName + "-JVM-BOSS"), newEventLoop(LOCAL, 1, threadName))
                .channel(LocalServerChannel.class)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))
                .localAddress(new LocalAddress(localChannelName))
                .childHandler(new RegistrationLocalHandlerServer(threadName, registrationWrapper));
    }

    EventLoopGroup workerEventLoop = null;
    if (tcpBootstrap != null || udpBootstrap != null) {
        workerEventLoop = newEventLoop(config.workerThreadPoolSize, threadName);
    }

    if (tcpBootstrap != null) {
        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            tcpBootstrap.channel(OioServerSocketChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            tcpBootstrap.channel(EpollServerSocketChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            tcpBootstrap.channel(KQueueServerSocketChannel.class);
        } else {
            tcpBootstrap.channel(NioServerSocketChannel.class);
        }

        // TODO: If we use netty for an HTTP server,
        // Beside the usual ChannelOptions the Native Transport allows to enable TCP_CORK which may come in handy if you implement a HTTP Server.

        tcpBootstrap
                .group(newEventLoop(1, threadName + "-TCP-BOSS"),
                        newEventLoop(1, threadName + "-TCP-REGISTRATION"))
                .option(ChannelOption.SO_BACKLOG, backlogConnectionCount)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))

                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new RegistrationRemoteHandlerServerTCP(threadName, registrationWrapper,
                        workerEventLoop));

        // have to check options.host for "0.0.0.0". we don't bind to "0.0.0.0", we bind to "null" to get the "any" address!
        if (hostName.equals("0.0.0.0")) {
            tcpBootstrap.localAddress(tcpPort);
        } else {
            tcpBootstrap.localAddress(hostName, tcpPort);
        }

        // android screws up on this!!
        tcpBootstrap.option(ChannelOption.TCP_NODELAY, !OS.isAndroid()).childOption(ChannelOption.TCP_NODELAY,
                !OS.isAndroid());
    }

    if (udpBootstrap != null) {
        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            udpBootstrap.channel(OioDatagramChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            udpBootstrap.channel(EpollDatagramChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            udpBootstrap.channel(KQueueDatagramChannel.class);
        } else {
            // windows and linux/mac that are incompatible with the native implementations
            udpBootstrap.channel(NioDatagramChannel.class);
        }

        // Netty4 has a default of 2048 bytes as upper limit for datagram packets, we want this to be whatever we specify
        FixedRecvByteBufAllocator recvByteBufAllocator = new FixedRecvByteBufAllocator(EndPoint.udpMaxSize);

        udpBootstrap
                .group(newEventLoop(1, threadName + "-UDP-BOSS"),
                        newEventLoop(1, threadName + "-UDP-REGISTRATION"))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))

                // a non-root user can't receive a broadcast packet on *nix if the socket is bound on non-wildcard address.
                // TODO: move broadcast to it's own handler, and have UDP server be able to be bound to a specific IP
                // OF NOTE: At the end in my case I decided to bind to .255 broadcast address on Linux systems. (to receive broadcast packets)
                .localAddress(udpPort) // if you bind to a specific interface, Linux will be unable to receive broadcast packets! see: http://developerweb.net/viewtopic.php?id=5722
                .childHandler(new RegistrationRemoteHandlerServerUDP(threadName, registrationWrapper,
                        workerEventLoop));

        // // have to check options.host for null. we don't bind to 0.0.0.0, we bind to "null" to get the "any" address!
        // if (hostName.equals("0.0.0.0")) {
        //     udpBootstrap.localAddress(hostName, tcpPort);
        // }
        // else {
        //     udpBootstrap.localAddress(udpPort);
        // }

        // Enable to READ from MULTICAST data (ie, 192.168.1.0)
        // in order to WRITE: write as normal, just make sure it ends in .255
        // in order to LISTEN:
        //    InetAddress group = InetAddress.getByName("203.0.113.0");
        //    socket.joinGroup(group);
        // THEN once done
        //    socket.leaveGroup(group), close the socket
        // Enable to WRITE to MULTICAST data (ie, 192.168.1.0)
        udpBootstrap.option(ChannelOption.SO_BROADCAST, false).option(ChannelOption.SO_SNDBUF, udpMaxSize);
    }
}

From source file:eu.xworlds.util.raknet.RaknetServer.java

License:Open Source License

/**
 * Hidden constructor./*from  www .j a  va2  s.  c  o  m*/
 * 
 * @param addresses
 *            the addresses to bind to.
 * @param serverListeners
 *            the listeners.
 * @param recvBuffer
 *            the recv buffer size.
 * @param sendBuffer
 *            the send buffer size.
 * @param sGroup
 *            the sender nio group.
 * @param rGroup
 *            the receiver nio group.
 * @param sessionReadTimeout
 *            the raknet session read timeout in milliseconds
 * @param pFactories
 *            the factories to create additional raknet pipeline handlers
 * @param hFactories
 *            the factories to register additional raknet message handlers
 * @param mFactories
 *            the factories to register additional raknet message classes
 */
RaknetServer(InetSocketAddress[] addresses, RaknetServerListener[] serverListeners, int recvBuffer,
        int sendBuffer, NioEventLoopGroup sGroup, NioEventLoopGroup rGroup, int sessionReadTimeout,
        RaknetPipelineFactory[] pFactories, RaknetMessageFactory[] mFactories,
        RaknetHandlerFactory[] hFactories) {
    // this.addresses = addresses;
    this.serverListeners = serverListeners;
    this.recvBuffer = recvBuffer;
    this.sendBuffer = sendBuffer;
    this.senderGroup = sGroup;
    this.receiverGroup = rGroup;

    this.pipelineFactories = pFactories;
    this.handlerFactories = hFactories;
    this.messageFactories = mFactories;

    this.sessions = CacheBuilder.newBuilder().maximumSize(1000). // TODO read from builder
            expireAfterAccess(sessionReadTimeout, TimeUnit.MILLISECONDS)
            .removalListener(new SessionRemovalListener()).build(new SessionCacheLoader());

    final Bootstrap b = new Bootstrap();
    b.group(this.receiverGroup).channel(NioDatagramChannel.class)
            .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            .option(ChannelOption.SO_RCVBUF, Integer.valueOf(this.recvBuffer))
            .option(ChannelOption.SO_SNDBUF, Integer.valueOf(this.sendBuffer))
            .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(this.recvBuffer))
            .handler(new RaknetInitializer());

    for (final InetSocketAddress address : addresses) {
        this.listenFutures.add(b.bind(address).addListener(new BindListener()));
    }
}

From source file:github.com.cp149.netty.server.NettyappenderServer.java

License:Apache License

public void run() throws Exception {

    try {//from   w  w w  .  j a v a  2s.co  m
        bootstrap = new ServerBootstrap();
        final EventExecutorGroup executor = new DefaultEventExecutorGroup(4);

        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_RCVBUF, 65535).childOption(ChannelOption.SO_SNDBUF, 2048)
                .childOption(ChannelOption.SO_REUSEADDR, true) //reuse address
                .childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false))// heap buf 's better               
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        //                     ch.pipeline().addLast( new MarshallingEncoder(MarshallUtil.createProvider()));
                        //                     ch.pipeline().addLast(new CompatibleObjectDecoder());
                        //                     ch.pipeline().addLast(new ObjectEncoder(),
                        //                                  new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                        ch.pipeline().addLast(new MarshallingDecoder(MarshallUtil.createUnProvider()));

                        ch.pipeline().addLast(executor, new NettyappenderServerHandler());
                        //
                    }
                });

        bootstrap.bind(port).sync();

    } finally {

    }
    // bootstrap = new ServerBootstrap(new
    // NioServerSocketChannelFactory(Executors.newFixedThreadPool(4),
    // Executors.newFixedThreadPool(4)));
    // final ExecutionHandler executionHandler = new ExecutionHandler(new
    // OrderedMemoryAwareThreadPoolExecutor(4, 1024 * 1024 * 300, 1024 *
    // 1024 * 300 * 2));
    // bootstrap.setOption("tcpNoDelay", true);
    // bootstrap.setOption("keepAlive", true);
    // // bootstrap.setOption("writeBufferHighWaterMark", 100 * 64 * 1024);
    // // bootstrap.setOption("sendBufferSize", 1048576);
    // bootstrap.setOption("receiveBufferSize", 1048576*10 );
    //
    // // Set up the pipeline factory.
    // bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    // public ChannelPipeline getPipeline() throws Exception {
    // return Channels.pipeline(executionHandler, new
    // MarshallingDecoder(createProvider(createMarshallerFactory(),
    // createMarshallingConfig())),
    // new NettyappenderServerHandler());
    // }
    // });

    // // Bind and start to accept incoming connections.
    // bootstrap.bind(new InetSocketAddress(port));
    //       LoggerFactory.getLogger(this.getClass()).info("start server at" +
    //             port);
}

From source file:io.advantageous.conekt.http.impl.HttpClientImpl.java

License:Open Source License

private void applyConnectionOptions(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }/*  w w  w . j  ava2  s  . c  o  m*/
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, options.isReuseAddress());
}

From source file:io.advantageous.conekt.http.impl.HttpServerImpl.java

License:Open Source License

private void applyConnectionOptions(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  va2s  . 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.option(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:io.advantageous.conekt.net.impl.NetClientImpl.java

License:Open Source License

private void applyConnectionOptions(Bootstrap bootstrap) {
    bootstrap.option(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }/*from w  w w . j  a  va  2s  .c o  m*/
    if (options.getReceiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, options.getReceiveBufferSize());
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR,
                new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    if (options.getSoLinger() != -1) {
        bootstrap.option(ChannelOption.SO_LINGER, options.getSoLinger());
    }
    if (options.getTrafficClass() != -1) {
        bootstrap.option(ChannelOption.IP_TOS, options.getTrafficClass());
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, options.isTcpKeepAlive());
}

From source file:io.advantageous.conekt.net.impl.NetServerImpl.java

License:Open Source License

private void applyConnectionOptions(ServerBootstrap bootstrap) {
    bootstrap.childOption(ChannelOption.TCP_NODELAY, options.isTcpNoDelay());
    if (options.getSendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, options.getSendBufferSize());
    }//from  w  ww.  j a  v  a 2  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.option(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:io.atomix.catalyst.transport.netty.NettyClient.java

License:Apache License

@Override
public CompletableFuture<Connection> connect(Address address) {
    Assert.notNull(address, "address");
    ThreadContext context = ThreadContext.currentContextOrThrow();
    CompletableFuture<Connection> future = new ComposableFuture<>();

    LOGGER.info("Connecting to {}", address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(transport.eventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  w ww . j a v a  2 s .c  o  m*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (transport.properties().sslEnabled()) {
                        pipeline.addFirst(
                                new SslHandler(new NettyTls(transport.properties()).initSslEngine(true)));
                    }
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0,
                            4, 0, 4));
                    pipeline.addLast(
                            new NettyHandler(connections, future::complete, context, transport.properties()));
                }
            });

    bootstrap.option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, transport.properties().connectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, ALLOCATOR);

    if (transport.properties().sendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize());
    }
    if (transport.properties().receiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize());
    }

    bootstrap.connect(address.socketAddress()).addListener(channelFuture -> {
        if (channelFuture.isSuccess()) {
            LOGGER.info("Connected to {}", address);
        } else {
            context.execute(() -> future.completeExceptionally(channelFuture.cause()));
        }
    });
    return future;
}

From source file:io.atomix.catalyst.transport.netty.NettyServer.java

License:Apache License

/**
 * Starts listening for the given member.
 *///  ww  w  .  j a  v a  2 s  . c o  m
private void listen(Address address, Consumer<Connection> listener, ThreadContext context) {
    channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE);

    handler = new ServerHandler(connections, listener, context, transport.properties());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(transport.eventLoopGroup()).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (transport.properties().sslEnabled()) {
                        pipeline.addFirst(
                                new SslHandler(new NettyTls(transport.properties()).initSslEngine(false)));
                    }
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0,
                            4, 0, 4));
                    pipeline.addLast(handler);
                }
            }).option(ChannelOption.SO_BACKLOG, transport.properties().acceptBacklog())
            .option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay())
            .option(ChannelOption.SO_REUSEADDR, transport.properties().reuseAddress())
            .childOption(ChannelOption.ALLOCATOR, ALLOCATOR)
            .childOption(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive());

    if (transport.properties().sendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize());
    }
    if (transport.properties().receiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize());
    }

    LOGGER.info("Binding to {}", address);

    ChannelFuture bindFuture = bootstrap.bind(address.socketAddress());
    bindFuture.addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            listening = true;
            context.executor().execute(() -> {
                LOGGER.info("Listening at {}", bindFuture.channel().localAddress());
                listenFuture.complete(null);
            });
        } else {
            context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause()));
        }
    });
    channelGroup.add(bindFuture.channel());
}