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:com.digitalpetri.modbus.master.ModbusTcpMaster.java

License:Apache License

public static CompletableFuture<Channel> bootstrap(ModbusTcpMaster master, ModbusTcpMasterConfig config) {
    CompletableFuture<Channel> future = new CompletableFuture<>();

    Bootstrap bootstrap = new Bootstrap();

    config.getBootstrapConsumer().accept(bootstrap);

    bootstrap.group(config.getEventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) config.getTimeout().toMillis())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*ww w.  ja  v  a  2  s .c o  m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(
                            new ModbusTcpCodec(new ModbusRequestEncoder(), new ModbusResponseDecoder()));
                    ch.pipeline().addLast(new ModbusTcpMasterHandler(master));
                }
            }).connect(config.getAddress(), config.getPort()).addListener((ChannelFuture f) -> {
                if (f.isSuccess()) {
                    future.complete(f.channel());
                } else {
                    future.completeExceptionally(f.cause());
                }
            });

    return future;
}

From source file:com.digitalpetri.modbus.slave.ModbusTcpSlave.java

License:Apache License

public CompletableFuture<ModbusTcpSlave> bind(String host, int port) {
    CompletableFuture<ModbusTcpSlave> bindFuture = new CompletableFuture<>();

    ServerBootstrap bootstrap = new ServerBootstrap();

    ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
        @Override/* w w  w  .ja  va  2 s.  c  o  m*/
        protected void initChannel(SocketChannel channel) throws Exception {
            channelCounter.inc();
            logger.info("channel initialized: {}", channel);

            channel.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
            channel.pipeline()
                    .addLast(new ModbusTcpCodec(new ModbusResponseEncoder(), new ModbusRequestDecoder()));
            channel.pipeline().addLast(new ModbusTcpSlaveHandler(ModbusTcpSlave.this));

            channel.closeFuture().addListener(future -> channelCounter.dec());
        }
    };

    config.getBootstrapConsumer().accept(bootstrap);

    bootstrap.group(config.getEventLoop()).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(initializer)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    bootstrap.bind(host, port).addListener((ChannelFuture future) -> {
        if (future.isSuccess()) {
            Channel channel = future.channel();
            serverChannels.put(channel.localAddress(), channel);
            bindFuture.complete(ModbusTcpSlave.this);
        } else {
            bindFuture.completeExceptionally(future.cause());
        }
    });

    return bindFuture;
}

From source file:com.digitalpetri.opcua.stack.client.UaTcpStackClient.java

License:Apache License

public static CompletableFuture<ClientSecureChannel> bootstrap(UaTcpStackClient client,
        Optional<ClientSecureChannel> existingChannel) {

    CompletableFuture<ClientSecureChannel> handshake = new CompletableFuture<>();

    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(client.getConfig().getEventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*  w ww .  j a  va 2s  . c o  m*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    UaTcpClientAcknowledgeHandler acknowledgeHandler = new UaTcpClientAcknowledgeHandler(client,
                            existingChannel, handshake);

                    channel.pipeline().addLast(acknowledgeHandler);
                }
            });

    try {
        URI uri = URI.create(client.getEndpointUrl());

        bootstrap.connect(uri.getHost(), uri.getPort()).addListener((ChannelFuture f) -> {
            if (!f.isSuccess()) {
                handshake.completeExceptionally(f.cause());
            }
        });
    } catch (Throwable t) {
        UaException failure = new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid,
                "endpoint URL invalid: " + client.getEndpointUrl());

        handshake.completeExceptionally(failure);
    }

    return handshake;
}

From source file:com.digitalpetri.opcua.stack.server.tcp.SocketServer.java

License:Apache License

private SocketServer(InetSocketAddress address) {
    this.address = address;

    bootstrap.group(Stack.sharedEventLoop()).handler(new LoggingHandler(SocketServer.class))
            .channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from  w  w  w  .  java2s .  c om
                protected void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new UaTcpServerHelloHandler(SocketServer.this));
                }
            });
}

From source file:com.diwayou.hybrid.remoting.netty.NettyRemotingServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override/*from   ww w . ja  v a 2s. com*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker)
                    .channel(NioServerSocketChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .option(ChannelOption.SO_KEEPALIVE, false)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new NettyEncoder(), //
                                    new NettyDecoder(), //
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                                    new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        // ????
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}

From source file:com.ebay.jetstream.http.netty.client.HttpClient.java

License:MIT License

private void createChannelPipeline() {

    if (isPipelineCreated())
        return;/*from w  w w  .ja  v  a 2  s .  c om*/

    m_workerGroup = new NioEventLoopGroup(getConfig().getNumWorkers(),
            new NameableThreadFactory("Jetstream-HttpClientWorker"));
    m_bootstrap = new Bootstrap();
    m_bootstrap.group(m_workerGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConfig().getConnectionTimeoutInSecs())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("timeout",
                            new IdleStateHandler(0, getConfig().getIdleTimeoutInSecs(), 0));
                    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
                    ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
                    ch.pipeline().addLast("aggregator",
                            new HttpObjectAggregator(m_config.getMaxContentLength()));
                    ch.pipeline().addLast(m_httpRequestHandler);
                }
            });

    if (getConfig().getRvcBufSz() > 0) {
        m_bootstrap.option(ChannelOption.SO_RCVBUF, (int) getConfig().getRvcBufSz());
    }

    if (getConfig().getSendBufSz() > 0) {
        m_bootstrap.option(ChannelOption.SO_SNDBUF, (int) getConfig().getSendBufSz());
    }
    createdPipeline();

}

From source file:com.ebay.jetstream.http.netty.server.Acceptor.java

License:MIT License

/**
 * @param rxSessionHandler/*  w  w w  .ja v a 2 s . c o m*/
 * @throws Exception
 */
public void bind(final HttpRequestHandler httpReqHandler, final HttpServerStatisticsHandler statisticsHandler)
        throws Exception {
    m_bossGroup = new NioEventLoopGroup(1, new NameableThreadFactory("NettyHttpServerAcceptor"));
    m_workerGroup = new NioEventLoopGroup(m_numIoProcessors,
            new NameableThreadFactory("NettyHttpServerWorker"));

    try {
        m_serverbootstrap = new ServerBootstrap();
        m_serverbootstrap.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("timeout", new IdleStateHandler((int) m_readIdleTimeout, 0, 0));
                        ch.pipeline().addLast("stats", statisticsHandler);
                        ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                        ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                        ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                        ch.pipeline().addLast("deflater", new HttpContentCompressor(1));
                        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(m_maxContentLength));
                        if (m_maxKeepAliveRequests > 0 || m_maxKeepAliveTimeout > 0) {
                            ch.pipeline().addLast("keepAliveHandler",
                                    new KeepAliveHandler(m_maxKeepAliveRequests, m_maxKeepAliveTimeout));
                        }
                        ch.pipeline().addLast("handler", httpReqHandler);

                    }

                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.SO_KEEPALIVE, false);

        if (m_config.getRvcBufSz() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_RCVBUF, (int) m_config.getRvcBufSz());
        }

        if (m_config.getSendBufSz() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_SNDBUF, (int) m_config.getSendBufSz());
        }

    } catch (Exception t) {
        throw t;
    }

    m_acceptorSocket = new InetSocketAddress(m_ipAddress, m_tcpPort);
    m_serverbootstrap.bind(m_acceptorSocket).sync();

    if (!m_ipAddress.isLoopbackAddress() && !m_ipAddress.isAnyLocalAddress()) {
        // Add lookback if not bind
        m_localAcceptorSocket = new InetSocketAddress("127.0.0.1", m_tcpPort);
        m_serverbootstrap.bind(m_localAcceptorSocket).sync();
    }
}

From source file:com.ebay.jetstream.messaging.transport.netty.eventconsumer.Acceptor.java

License:MIT License

/**
 * @param rxSessionHandler/*ww w .j  ava 2s  .  c om*/
 * @throws Exception
 */
public void bind(EventProducerSessionHandler rxSessionHandler) throws Exception {

    m_rxSessionHandler = rxSessionHandler;
    m_bossGroup = new NioEventLoopGroup(1,
            new NameableThreadFactory("NettyAcceptor-" + m_tc.getTransportName()));
    m_workerGroup = new NioEventLoopGroup(m_numIoProcessors,
            new NameableThreadFactory("NettyReceiver-" + m_tc.getTransportName()));

    try {
        m_serverbootstrap = new ServerBootstrap();
        m_serverbootstrap.group(m_bossGroup, m_workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addFirst("msghandler", m_rxSessionHandler);

                        StreamMessageDecoder decoder = new StreamMessageDecoder(
                                ClassResolvers.weakCachingConcurrentResolver(null));
                        ch.pipeline().addBefore("msghandler", "msgdecoder", decoder);
                        ch.pipeline().addBefore("msgdecoder", "kryoEcnoder", new KryoObjectEncoder());
                        ch.pipeline().addBefore("kryoEcnoder", "msgencoder", new NettyObjectEncoder());

                        if (m_enableCompression) {

                            ch.pipeline().addBefore("msgencoder", "decompressor",
                                    new MessageDecompressionHandler(false, 250000));

                            ch.pipeline().addBefore("decompressor", "idleTimeoutHandler",
                                    new IdleStateHandler((int) m_readIdleTimeout, 0, 0));
                        } else
                            ch.pipeline().addBefore("msgencoder", "idleTimeoutHandler",
                                    new IdleStateHandler((int) m_readIdleTimeout, 0, 0));

                    }
                }).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .childOption(ChannelOption.SO_KEEPALIVE, isTcpKeepAlive());

        if (m_tc.getReceivebuffersize() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_RCVBUF, m_tc.getReceivebuffersize());
        }

        if (m_tc.getSendbuffersize() > 0) {
            m_serverbootstrap.childOption(ChannelOption.SO_SNDBUF, m_tc.getSendbuffersize());
        }

    } catch (Exception t) {
        throw t;
    }

    // we are given a port from DNS. We will check if it is taken. If it is
    // we will increment the port # by 10 and keep trying 10 times.
    // adding this feature so that we can operate the cluster on a single
    // node. Very useful for debugging and also for demos.

    int retryCount = 20;
    int port = m_tcpPort;

    while (retryCount-- > 0) {
        if (isPortAvailable(port))
            break;
        port += 1;

    }

    if (retryCount == 0)
        return; // we did not find a port to bind

    m_tcpPort = port;

    LOGGER.info("Acceptor bound to port" + m_tcpPort);

}

From source file:com.ebay.jetstream.messaging.transport.netty.eventproducer.EventProducer.java

License:MIT License

/**
 * //from   ww  w. j a  v  a  2  s .c o  m
 */
private void createChannelPipeline() {

    m_group = new NioEventLoopGroup(m_transportConfig.getNumConnectorIoProcessors(),
            new NameableThreadFactory("NettySender-" + m_transportConfig.getTransportName()));
    m_bootstrap = new Bootstrap();
    m_bootstrap.group(m_group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, m_transportConfig.getTcpKeepAlive())
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, m_transportConfig.getConnectionTimeoutInSecs() * 1000)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    StreamMessageDecoder decoder = new StreamMessageDecoder(ClassResolvers.cacheDisabled(null));

                    if (m_autoFlushHandler != null) {
                        ch.pipeline().addLast(new EventConsumerStatisticsHandler(),
                                new MessageCompressionHandler(),
                                new IdleStateHandler(m_transportConfig.getIdleTimeoutInSecs(), 0, 0),
                                m_autoFlushHandler, decoder, new NettyObjectEncoder(), new KryoObjectEncoder(),
                                m_ecSessionHandler);
                    } else {
                        ch.pipeline().addLast(new EventConsumerStatisticsHandler(),
                                new MessageCompressionHandler(), decoder, new NettyObjectEncoder(),
                                new KryoObjectEncoder(), m_ecSessionHandler);
                    }
                }
            });

    if (m_transportConfig.getReceivebuffersize() > 0) {
        m_bootstrap.option(ChannelOption.SO_RCVBUF, m_transportConfig.getReceivebuffersize());
    }

    if (m_transportConfig.getSendbuffersize() > 0) {
        m_bootstrap.option(ChannelOption.SO_SNDBUF, m_transportConfig.getSendbuffersize());
    }
}

From source file:com.eightkdata.mongowp.server.wp.NettyMongoServer.java

License:Open Source License

@Override
protected void startUp() throws Exception {
    LOGGER.info("Listening MongoDB requests on port " + port);

    connectionGroup = new NioEventLoopGroup(0,
            new ThreadFactoryBuilder().setNameFormat("netty-connection-%d").build());
    workerGroup = new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("netty-worker-%d").build());

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(connectionGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from   w  ww  .  j  ava 2  s .c  o m
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    buildChildHandlerPipeline(socketChannel.pipeline());
                }
            }) // TODO: set TCP channel options?
    ;

    ChannelFuture channelFuture = bootstrap.bind(port).awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        workerGroup.shutdownGracefully();
        connectionGroup.shutdownGracefully();
    }
}