Example usage for io.netty.channel ChannelOption TCP_NODELAY

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

Introduction

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

Prototype

ChannelOption TCP_NODELAY

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

Click Source Link

Usage

From source file:deven.monitor.client.MonitorClient.java

License:Apache License

private void init() {
    System.out.println("--> initializing connection to " + host + ":" + port);

    group = new NioEventLoopGroup();
    try {//from  www .j  a va2  s.c  o m
        CommandInit si = new CommandInit(null, false);
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(si);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);

        // Make the connection attempt.
        channel = b.connect(host, port).syncUninterruptibly();

        // want to monitor the connection to the server s.t. if we loose the
        // connection, we can try to re-establish it.
        ClientClosedListener ccl = new ClientClosedListener(this);
        channel.channel().closeFuture().addListener(ccl);

        System.out.println(channel.channel().localAddress() + " -> open: " + channel.channel().isOpen()
                + ", write: " + channel.channel().isWritable() + ", reg: " + channel.channel().isRegistered());

    } catch (Throwable ex) {
        System.out.println("failed to initialize the client connection " + ex.toString());
        ex.printStackTrace();
    }

}

From source file:diskCacheV111.doors.NettyLineBasedDoor.java

License:Open Source License

@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    try (CDC ignored = CDC.reset(getNucleus().getThisAddress())) {
        Transfer.initSession(false, true);
        cdc = new CDC();
    }//  w ww .ja v a2 s  .c om

    channel = ctx.channel();
    channel.config().setOption(ChannelOption.ALLOW_HALF_CLOSURE, true);
    channel.config().setOption(ChannelOption.TCP_NODELAY, true);
    channel.config().setOption(ChannelOption.SO_KEEPALIVE, true);
}

From source file:divconq.web.WebModule.java

License:Open Source License

public void goOnline() {
    this.listenlock.lock();

    try {//from w w w  .j a v  a2  s . c o m
        // don't try if already in online mode
        if (this.activelisteners.size() > 0)
            return;

        // typically we should have an extension, unless we are supporting RPC only
        // TODO if (WebSiteManager.instance.getDefaultExtension() == null) 
        //   log.warn(0, "No default extension for web server");

        for (final XElement httpconfig : this.config.selectAll("HttpListener")) {
            final boolean secure = "True".equals(httpconfig.getAttribute("Secure"));
            int httpport = (int) StringUtil.parseInt(httpconfig.getAttribute("Port"), secure ? 443 : 80);

            // -------------------------------------------------
            // message port
            // -------------------------------------------------
            ServerBootstrap b = new ServerBootstrap();

            // TODO consider using shared EventLoopGroup
            // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#25.0

            b.group(Hub.instance.getEventLoopGroup()).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .option(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (secure) {
                                SniHandler ssl = new SniHandler(WebModule.this.siteman);

                                //SslHandler ssl = new SslHandler(WebModule.this.siteman.findSslContextFactory("root").getServerEngine()); 

                                pipeline.addLast("ssl", ssl);
                            }

                            //pipeline.addLast("codec-http", new HttpServerCodec());
                            //pipeline.addLast("aggregator", new HttpObjectAggregator(65536));

                            pipeline.addLast("decoder", new HttpRequestDecoder(4096, 8192, 262144));
                            pipeline.addLast("encoder", new HttpResponseEncoder());

                            pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

                            // TODO maybe - but currently we selectively compress files which is more efficient
                            // this can also be a cached & compressed response that way
                            //pipeline.addLast("deflater", new HttpContentCompressor());

                            pipeline.addLast("handler", new ServerHandler(httpconfig, WebModule.this.siteman));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // but also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(httpport).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("Web Server listening - now listening for HTTP on TCP port " + httpport);
                    this.activelisteners.put(httpport, bfuture.channel());
                } else
                    Logger.error("Web Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.error("Web Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("Web Server errored while binding: " + x);
            }
        }
    } finally {
        this.listenlock.unlock();
    }

    this.siteman.online();

    //for (IWebExtension ext : WebSiteManager.instance.extensions.values())
    //   ext.online();
}

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
 *//*ww  w  . j a v a 2  s  .  c  o m*/
@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
 *///from ww  w  .j a  va2s . c  om
@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.jangos.realm.RealmServer.java

License:Apache License

/**
 * Main of the RealmServer program.//from   w w  w. j  av a  2  s .c  o m
 *
 * @param args the command line arguments
 * @throws InterruptedException in case of interruption of the running
 * process.
 */
public static void main(String[] args) throws InterruptedException {

    logger.info("Starting JaNGOS realm server version " + VERSION + ".");
    logger.info("JaNGOS is an opensource project, check-out : https://github.com/Warkdev/JaNGOSRealm !");

    realm.setOffline(false);
    rs.save(realm);

    logger.info("Realm configuration: ");
    logger.info("Name: " + realm.getName());
    logger.info("Address: " + realm.getAddress() + ":" + realm.getPort());
    logger.info("Type: " + realm.getRealmtype().getType());
    logger.info("Timezone: " + realm.getRealmtimezone().getName());
    logger.info("Population: " + realm.getPopulation());
    logger.info("Players: " + realm.getCountPlayers() + "/" + realm.getMaxPlayers());

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new RealmPacketDecoder(), new RealmPacketEncoder(), new RealmAuthHandler(),
                                new ReadTimeoutHandler(TIMEOUT), new CharacterHandler());
                    }
                });

        ChannelFuture f;

        // Start the server.   
        try {
            HOST = InetAddress.getByAddress(realm.getAddress().getBytes());
            f = b.bind(HOST, PORT).sync();
            logger.info("JaNGOS realm server started listening on " + HOST.getHostAddress() + ":" + PORT);
        } catch (UnknownHostException ex) {
            f = b.bind(PORT);
            logger.info("JaNGOS realm server started listening on port " + PORT);
        }

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        logger.info("JaNGOS realm server shutting down.");

        // Indicating that this realm is offline.
        realm.setOffline(true);
        rs.save(realm);

        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:eu.matejkormuth.rpgdavid.starving.remote.RemoteConnectionServer.java

License:Open Source License

private void initializeNetty() {
    // Initialize Netty.
    this.bossGroup = new NioEventLoopGroup(1);
    this.workerGroup = new NioEventLoopGroup(1);

    this.bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ServerChannelInitializer()).option(ChannelOption.TCP_NODELAY, false)
            .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, false);
}

From source file:eu.matejkormuth.rpgdavid.starving.remote.RemoteConnetionClient.java

License:Open Source License

private void initializeNetty() {
    this.eventGroup = new NioEventLoopGroup(1);

    this.bootstrap = new Bootstrap();
    this.bootstrap.group(eventGroup).channel(NioSocketChannel.class).handler(new ClientChannelInitializer())
            .option(ChannelOption.TCP_NODELAY, false).option(ChannelOption.SO_BACKLOG, 128);

}

From source file:eu.smartenit.sbox.interfaces.intersbox.client.InterSBoxClient.java

License:Apache License

/** sends vectors to inter-sbox server of remote sbox
 * //from  ww w .ja v a  2s  . c  o  m
 *  @param host : remote sbox identifier
 *  @param port : port number of remote sbox receiver
 *  @param cVector : compensation vector
 *  @param rvPresent : rVector presence indicator
 *  @param rVector : reference Vector 
 */
public void send(String host, int port, CVector cVector, boolean rvPresent, RVector rVector) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    logger.debug("InterSBoxClient send");
    try {
        final CVector cVector_ = cVector;
        final RVector rVector_ = rVector;
        final boolean rvPresent_ = rvPresent;
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8),
                                new StringEncoder(CharsetUtil.UTF_8),
                                new InterSBoxClientH(cVector_, rvPresent_, rVector_));
                    }
                });

        // Start the connection attempt.
        logger.debug("InterSBoxClient start connection attempt");
        Channel bf = b.connect(host, port).sync().channel();
        logger.debug("InterSBoxClient wait connection attempt");
        bf.closeFuture().sync();
        logger.debug("InterSBoxClient end connection attempt");
    } finally {
        group.shutdownGracefully();
    }
    logger.debug("InterSBoxClient send finish");
}

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

License:Apache License

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

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

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

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

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

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

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

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

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

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

                        System.out.println(getNonZeroNumQueuedEnvelopes());

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