Example usage for io.netty.channel ChannelInitializer ChannelInitializer

List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer

Introduction

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

Prototype

ChannelInitializer

Source Link

Usage

From source file:com.doctor.netty5.example.factorial_algorithm.FactorialClient.java

License:Apache License

public void start() throws InterruptedException {
    NioEventLoopGroup workersGroup = new NioEventLoopGroup(1);

    try {/*  w w  w .j a  va2  s.  c om*/
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workersGroup).channel(NioSocketChannel.class).remoteAddress(host, port)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NumberEncoder());
                        ch.pipeline().addLast(new BigIntegerDecoder());
                        ch.pipeline().addLast(new FactorialClientHandler());
                    }
                });

        ChannelFuture channelFuture = bootstrap.connect().sync();
        channelFuture.channel().closeFuture().sync();

    } finally {
        workersGroup.shutdownGracefully();
    }
}

From source file:com.doctor.netty5.example.factorial_algorithm.FactorialServer.java

License:Apache License

public void start() throws InterruptedException {
    ServerBootstrap bootstrap = new ServerBootstrap();
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*from w ww.j a  va2s .c  o  m*/
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(port)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NumberEncoder());
                        ch.pipeline().addLast(new BigIntegerDecoder());
                        ch.pipeline().addLast(new FactorialServerHandler());
                    }
                });

        ChannelFuture channelFuture = bootstrap.bind().sync();
        System.out.println(FactorialServer.class.getName() + " started and listen on port:"
                + channelFuture.channel().localAddress());

        channelFuture.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.doctor.netty5.example.http.helloworld.HelloWorldServer.java

License:Apache License

public void start() throws InterruptedException {
    ServerBootstrap bootstrap = new ServerBootstrap();
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*from  www  .  ja  v  a2 s.co m*/
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(port)
                .option(ChannelOption.SO_BACKLOG, 1024).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec());
                        ch.pipeline().addLast(new HelloWorldServerHandler());
                    }
                });

        ChannelFuture channelFuture = bootstrap.bind().sync();
        System.out.println(HelloWorldServer.class.getName() + " started and listen on port:"
                + channelFuture.channel().localAddress());

        channelFuture.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

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 va2s.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/*from ww w . j  a va 2  s .co  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/*from w w w  .jav  a  2  s. c  o m*/
 * @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 w  w w. j  a  va  2s .  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.mongoserver.MongoServer.java

License:Open Source License

public void run() {
    // TODO: provide custom ThreadFactories to the EventLoopGroup to name threads correctly?
    connectionGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {/*from w w  w .  j  av  a 2  s .  com*/
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(connectionGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        buildChildHandlerPipeline(socketChannel.pipeline());
                    }
                })
        // TODO: set TCP channel options?
        ;

        ChannelFuture channelFuture = bootstrap.bind(port).awaitUninterruptibly();

        try {
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException interruptedException) {
            LOGGER.error("Error", interruptedException);
            // TODO: perform proper shutdown
        } catch (Throwable throwable) {
            LOGGER.error("Error", throwable);
            // TODO: perform proper shutdown
        }
    } finally {
        workerGroup.shutdownGracefully();
        connectionGroup.shutdownGracefully();
    }
}

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   ww  w . j a  va2s  . 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();
    }
}

From source file:com.example.client.ClientChannelInitializerConfigurer.java

License:Apache License

static ChannelInitializer<SocketChannel> applyConfigurer(
        final Iterable<ClientChannelInitializerConfigurer> configurers) {
    final ImmutableList<ClientChannelInitializerConfigurer> list = Lists.immutable.ofAll(configurers);
    return new ChannelInitializer<SocketChannel>() {
        @Override/*  w w  w . j a  va 2 s  . co  m*/
        protected void initChannel(final SocketChannel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            list.injectInto(pipeline, (pipe, config) -> pipe.addLast(config.handlerAdapter()));
        }
    };
}