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.github.jrialland.ajpclient.pool.ChannelPool.java

License:Apache License

private static NettyConnectionPool createPool(final String host, final int port,
        final ChannelPoolMonitorImpl monitor) {
    final Bootstrap bootstrap = Channels.newBootStrap(host, port);

    final NettyConnectionPoolBuilder ncb = new NettyConnectionPoolBuilder(0, 200, 1000);

    ncb.withBootstrapProvider(new BootstrapProvider() {

        @Override/*  w w  w.  j a  v  a 2s.  c om*/
        public Bootstrap createBootstrap(final PoolProvider pp) {
            return bootstrap;
        }
    });

    ncb.withConnectionInfoProvider(new ConnectionInfoProvider() {

        @Override
        public ConnectionInfo connectionInfo(final PoolProvider pp) {
            final InetSocketAddress remoteAddr = new InetSocketAddress(host, port);
            return new ConnectionInfo(remoteAddr, null, new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(final Channel ch) throws Exception {
                    Channels.initChannel(ch);
                }
            });
        }
    });

    /**
     * Always close on exception
     */
    ncb.withContextExceptionHandler(new ContextExceptionHandler() {
        @Override
        public boolean close(final Throwable arg0, final PoolProvider arg1) {
            return true;
        }
    });

    final NettyConnectionPool pool = ncb.build();
    pool.addListener(monitor);
    return pool;
}

From source file:com.github.jrialland.ajpclient.pool.Channels.java

License:Apache License

private static Channel connect(final String host, final int port, final EventLoopGroup eventLoopGroup) {
    final Bootstrap bootstrap = newBootStrap(host, port, eventLoopGroup);
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override//from   w  ww .ja  v  a 2  s.co  m
        protected void initChannel(final Channel ch) throws Exception {
            Channels.initChannel(ch);
        }
    });
    try {
        final ChannelFuture cf = bootstrap.connect().sync();
        final Channel channel = cf.channel();
        if (channel == null) {
            throw new IllegalStateException();
        } else {
            return channel;
        }
    } catch (final InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.liyp.netty.App.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {//w  w w  .j a  v a2  s  .  c o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ReplayingDecoder() {
                            @Override
                            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
                                    throws Exception {
                                short magicHeader = in.readShort();
                                logger.debug("Receive magic header: {}.", magicHeader);
                                if (magicHeader != HEADER) {
                                    logger.error("Receive illegal magic header: {}, close channel: {}.",
                                            magicHeader, ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                short dataLen = in.readShort();
                                logger.debug("Receive message data length: {}.", dataLen);
                                if (dataLen < 0) {
                                    logger.error("Data length is negative, close channel: {}.",
                                            ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                ByteBuf payload = in.readBytes(dataLen);
                                String cloudMsg = payload.toString(CharsetUtil.UTF_8);
                                logger.debug("Receive data: {}.", cloudMsg);
                                out.add(cloudMsg);
                            }
                        }).addLast(new MessageToByteEncoder<String>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out)
                                    throws Exception {
                                out.writeBytes(msg.getBytes());
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("start receive msg...");
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                logger.info("receive msg: {}", msg);
                                logger.info("echo msg");
                                ctx.writeAndFlush(msg);
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("9999");
        f.channel().closeFuture().sync();
    } finally {
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}

From source file:com.github.liyp.netty.HandlerChainApp.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {//from  w w w.  ja  v  a 2s.c  om
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("1");
                                ctx.fireChannelActive();
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("2");
                                ctx.fireChannelActive();
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("3");
                                ctx.fireChannelActive();
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("9999");
        f.channel().closeFuture().sync();
    } finally {
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}

From source file:com.github.milenkovicm.kafka.connection.ControlKafkaBroker.java

License:Apache License

@Override
protected ChannelInitializer<SocketChannel> pipeline() {
    return new ChannelInitializer<SocketChannel>() {
        @Override/*from  w  w w  .j a v a  2  s.c  o m*/
        public void initChannel(SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new LengthFieldBasedFrameDecoder(Short.MAX_VALUE, 0, 4, 0, 4));
            if (properties.get(ProducerProperties.NETTY_DEBUG_PIPELINE)) {
                pipeline.addLast(new LoggingHandler());
            }
            pipeline.addLast(new MetadataHandler(properties));
            pipeline.addLast(new TerminalHandler());
        }
    };
}

From source file:com.github.milenkovicm.kafka.connection.DataKafkaBroker.java

License:Apache License

@Override
protected ChannelInitializer<SocketChannel> pipeline() {
    return new ChannelInitializer<SocketChannel>() {
        @Override/*  ww  w  . j av  a  2s.co m*/
        public void initChannel(SocketChannel channel) throws Exception {
            final ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new LengthFieldBasedFrameDecoder(Short.MAX_VALUE, 0, 4, 0, 4));
            pipeline.addLast(metricHandler);

            if (properties.get(ProducerProperties.NETTY_DEBUG_PIPELINE)) {
                pipeline.addLast(new LoggingHandler());
            }

            if (properties.get(ProducerProperties.NETTY_HANDLER_COMPOSITE)) {
                pipeline.addLast(new CompositeProducerHandler(topicName, properties));
            } else {
                pipeline.addLast(new CopyProducerHandler(topicName, properties));
            }
            pipeline.addLast(new TerminalHandler());
        }
    };
}

From source file:com.github.nettybook.ch4.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();

    try {//from ww  w.ja  v  a 2  s  .  c om
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EchoClientHandler1());
                p.addLast(new LoggingHandler());
            }
        });

        ChannelFuture f = b.connect("localhost", 8888).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.github.pgasync.impl.netty.NettyPgProtocolStream.java

License:Apache License

ChannelInitializer<Channel> newProtocolInitializer(ChannelHandler onActive) {
    return new ChannelInitializer<Channel>() {
        @Override//from  w  w w .j  a v a  2  s.co m
        protected void initChannel(Channel channel) throws Exception {
            if (useSsl) {
                channel.pipeline().addLast(newSslInitiator());
            }
            channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 1, 4, -4, 0, true));
            channel.pipeline().addLast(new ByteBufMessageDecoder());
            channel.pipeline().addLast(new ByteBufMessageEncoder());
            channel.pipeline().addLast(newProtocolHandler());
            channel.pipeline().addLast(onActive);
        }
    };
}

From source file:com.github.sinsinpub.pero.manual.proxyhandler.ProxyServer.java

License:Apache License

/**
 * Starts a new proxy server with disabled authentication for testing purpose.
 * /*from  ww w.j  av a2  s .  co  m*/
 * @param useSsl {@code true} if and only if implicit SSL is enabled
 * @param testMode the test mode
 * @param username the expected username. If the client tries to authenticate with a different
 *            username, this server will fail the authentication request.
 * @param password the expected password. If the client tries to authenticate with a different
 *            password, this server will fail the authentication request.
 * @param destination the expected destination. If the client requests proxying to a different
 *            destination, this server will reject the connection request.
 */
protected ProxyServer(final boolean useSsl, TestMode testMode, InetSocketAddress destination, String username,
        String password, int bindPort, boolean logging) {

    this.testMode = testMode;
    this.destination = destination;
    this.username = username;
    this.password = password;

    ServerBootstrap b = new ServerBootstrap();
    b.channel(NioServerSocketChannel.class);
    if (logging) {
        b.handler(new LoggingHandler(LogLevel.INFO));
    }
    b.group(StaticContextProvider.group);
    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (useSsl) {
                p.addLast(StaticContextProvider.serverSslCtx.newHandler(ch.alloc()));
            }

            configure(ch);
        }
    });

    ch = (ServerSocketChannel) b.bind(NetUtil.LOCALHOST, bindPort).syncUninterruptibly().channel();
}

From source file:com.github.sparkfy.network.client.TransportClientFactory.java

License:Apache License

/** Create a completely new {@link TransportClient} to the remote address. */
private TransportClient createClient(InetSocketAddress address) throws IOException {
    logger.debug("Creating new connection to " + address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(socketChannelClass)
            // Disable Nagle's Algorithm since we don't want packets to wait
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
            .option(ChannelOption.ALLOCATOR, pooledAllocator);

    final AtomicReference<TransportClient> clientRef = new AtomicReference<TransportClient>();
    final AtomicReference<Channel> channelRef = new AtomicReference<Channel>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override/*from w  ww  .  ja v a  2 s.c o m*/
        public void initChannel(SocketChannel ch) {
            TransportChannelHandler clientHandler = context.initializePipeline(ch);
            clientRef.set(clientHandler.getClient());
            channelRef.set(ch);
        }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.awaitUninterruptibly(conf.connectionTimeoutMs())) {
        throw new IOException(
                String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
        throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
        for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
            clientBootstrap.doBootstrap(client, channel);
        }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
        long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
        logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
        client.close();
        throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.debug("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)", address,
            (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
}