Example usage for io.netty.buffer PooledByteBufAllocator DEFAULT

List of usage examples for io.netty.buffer PooledByteBufAllocator DEFAULT

Introduction

In this page you can find the example usage for io.netty.buffer PooledByteBufAllocator DEFAULT.

Prototype

PooledByteBufAllocator DEFAULT

To view the source code for io.netty.buffer PooledByteBufAllocator DEFAULT.

Click Source Link

Usage

From source file:dbseer.middleware.client.MiddlewareClient.java

License:Apache License

public void run() {
    // debug info
    Log.debug(String.format("host = %s", host));
    Log.debug(String.format("port = %d", port));
    Log.debug(String.format("log path = %s", logPath));

    // client needs to handle incoming messages from the middleware as well.
    EventLoopGroup group = new NioEventLoopGroup(4);

    try {/*from   ww  w  .  j  a v a2  s  . com*/
        // attach shutdown hook.
        MiddlewareClientShutdown shutdownThread = new MiddlewareClientShutdown(this);
        Runtime.getRuntime().addShutdownHook(shutdownThread);

        File logDir = new File(logPath);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }

        final MiddlewareClient client = this;

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new IdleStateHandler(10, 0, 0));
                        p.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB));
                        p.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.ZLIB));
                        p.addLast(new MiddlewarePacketDecoder());
                        p.addLast(new MiddlewarePacketEncoder());
                        p.addLast(new MiddlewareClientHandler(client));
                    }
                });

        ChannelFuture f = b.connect(host, port).sync();
        channel = f.channel();
        Log.debug("Connected to the middleware.");

        MiddlewarePacket checkPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_CHECK_VERSION,
                MiddlewareConstants.PROTOCOL_VERSION);
        //         ByteBuf buf = Unpooled.buffer();
        //         buf.writeInt(MiddlewareConstants.PACKET_CHECK_VERSION);
        //         buf.writeInt(MiddlewareConstants.PROTOCOL_VERSION.getBytes("UTF-8").length);
        //         buf.writeBytes(MiddlewareConstants.PROTOCOL_VERSION.getBytes("UTF-8"));
        //         channel.writeAndFlush(buf);
        channel.writeAndFlush(checkPacket);

        channel.closeFuture().sync();
    } catch (Exception e) {
        if (e instanceof InterruptedException) {

        } else {
            setChanged();
            notifyObservers(new MiddlewareClientEvent(MiddlewareClientEvent.ERROR, e));
        }
        Log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
        this.stopExecutors();
        if (txLogFileRaw.exists()) {
            txLogFileRaw.delete();
        }
        if (txZipOutputStream != null) {
            try {
                txZipOutputStream.closeEntry();
                txZipOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            txZipOutputStream = null;
        }
    }
}

From source file:dbseer.middleware.server.MiddlewareServer.java

License:Apache License

public void run() throws Exception {
    // basic log info.
    Log.info(String.format("Listening port = %d", port));
    Log.info(String.format("DB log dir = %s", dbLogPath));
    Log.info(String.format("System log dir = %s", sysLogPath));

    // print server info.
    for (Server s : servers.values()) {
        s.printLogInfo();/*  w ww.  j  av  a  2s .c om*/
        // test MySQL/MariaDB connection using JDBC before we start anything.
        if (!s.testConnection()) {
            throw new Exception("Unable to connect to the MySQL server with the given credential.");
        } else if (!s.testMonitoringDir()) {
            throw new Exception("Specified monitoring directory and script do not exist.");
        }
    }

    // open named pipe.
    File checkPipeFile = new File(this.namedPipePath);
    if (checkPipeFile == null || !checkPipeFile.exists() || checkPipeFile.isDirectory()) {
        throw new Exception("Cannot open the named pipe for communication with dbseerroute. "
                + "You must run Maxscale with dbseerroute with correct named pipe first.");
    }

    namedPipeFile = new RandomAccessFile(this.namedPipePath, "rwd");
    if (namedPipeFile == null) {
        throw new Exception("Cannot open the named pipe for communication with dbseerroute. "
                + "You must run Maxscale with dbseerroute with correct named pipe first.");
    }

    // attach shutdown hook.
    MiddlewareServerShutdown shutdownThread = new MiddlewareServerShutdown(this);
    Runtime.getRuntime().addShutdownHook(shutdownThread);

    // let's start accepting connections.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(4);

    final MiddlewareServer server = this;
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .handler(new MiddlewareServerConnectionHandler(server))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new IdleStateHandler(10, 0, 0));
                        p.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB));
                        p.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.ZLIB));
                        p.addLast(new MiddlewarePacketDecoder());
                        p.addLast(new MiddlewarePacketEncoder());
                        p.addLast(new MiddlewareServerHandler(server));
                        //                     p.addLast(new MiddlewarePacketDecoder(), new MiddlewareServerHandler(server));
                    }
                });

        Log.info("Middleware is now accepting connections.");

        // bind and start accepting connections.
        ChannelFuture cf = b.bind(port).sync();

        // shutdown the server.
        if (cf != null) {
            cf.channel().closeFuture().sync();
        }
    } catch (Exception e) {
        Log.error(e.getMessage());
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        if (tailerExecutor != null && !tailerExecutor.isShutdown()) {
            tailerExecutor.shutdown();
        }
    }
}

From source file:de.jackwhite20.apex.udp.ApexDatagram.java

License:Open Source License

@Override
public Channel bootstrap(EventLoopGroup bossGroup, EventLoopGroup workerGroup, String ip, int port, int backlog,
        int readTimeout, int writeTimeout) throws Exception {

    logger.info("Bootstrapping datagram server");

    Bootstrap bootstrap = new Bootstrap().group(workerGroup).channel(PipelineUtils.getDatagramChannel())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(new DatagramUpstreamHandler());

    if (PipelineUtils.isEpoll()) {
        bootstrap.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);

        logger.debug("Epoll mode is now level triggered");
    }/* w w w .j a v a 2  s  . c  o  m*/

    return bootstrap.bind(ip, port).sync().channel();
}

From source file:de.jackwhite20.japs.server.network.initialize.ClusterPublisherChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(Channel channel) throws Exception {

    try {/*from   w  ww.ja v a 2s  . c  om*/
        channel.config().setOption(ChannelOption.IP_TOS, 0x18);
    } catch (ChannelException e) {
        // Not supported
    }
    channel.config().setAllocator(PooledByteBufAllocator.DEFAULT);

    channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4));
    channel.pipeline().addLast(new JSONObjectDecoder());
    channel.pipeline().addLast(new LengthFieldPrepender(4));
    channel.pipeline().addLast(new JSONObjectEncoder());
    channel.pipeline().addLast(clusterPublisher);
}

From source file:de.jackwhite20.japs.server.network.initialize.ServerChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(Channel channel) throws Exception {

    try {//ww w . ja  v  a  2  s . c  o m
        channel.config().setOption(ChannelOption.IP_TOS, 0x18);
    } catch (ChannelException e) {
        // Not supported
    }
    channel.config().setAllocator(PooledByteBufAllocator.DEFAULT);

    channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4));
    channel.pipeline().addLast(new JSONObjectDecoder());
    channel.pipeline().addLast(new LengthFieldPrepender(4));
    channel.pipeline().addLast(new JSONObjectEncoder());
    channel.pipeline().addLast(new Connection(jaPSServer, channel));
}

From source file:de.jackwhite20.japs.shared.pipeline.initialize.ClientChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(Channel channel) throws Exception {

    try {/*from w  w w.  j av a2  s  .c o  m*/
        channel.config().setOption(ChannelOption.IP_TOS, 0x18);
    } catch (ChannelException e) {
        // Not supported
    }
    channel.config().setAllocator(PooledByteBufAllocator.DEFAULT);

    channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4));
    channel.pipeline().addLast(new JSONObjectDecoder());
    channel.pipeline().addLast(new LengthFieldPrepender(4));
    channel.pipeline().addLast(new JSONObjectEncoder());
    channel.pipeline().addLast(nioSocketClient);
}

From source file:de.ocarthon.core.network.HttpClient.java

License:Apache License

private static Bootstrap defaultBootstrap() {
    if (defaultHttpBootstrap == null) {
        defaultHttpBootstrap = new Bootstrap();
        defaultHttpBootstrap.group(eventLoopGroup);
        defaultHttpBootstrap.option(ChannelOption.TCP_NODELAY, true);
        defaultHttpBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        defaultHttpBootstrap.channelFactory(channelFactory);
    }/*www.j  a va2s  .c  om*/
    return defaultHttpBootstrap;
}

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
 *//* w w  w  .j a  v a  2s  . 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   w  w  w .  j  a v  a2s  .com*/
@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.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  ww w . ja va  2 s .com*/

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