Example usage for io.netty.channel ChannelFuture channel

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

Introduction

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

Prototype

Channel channel();

Source Link

Document

Returns a channel where the I/O operation associated with this future takes place.

Usage

From source file:com.github.herong.rpc.netty.protobuf.demo2.Demo2ProtobufClient.java

License:Apache License

public void run() throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*  ww w  .  ja v  a2  s.c  o m*/
        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("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(Message.DTO.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new Demo2ProtobufClientHandler());

                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(host, port).sync();

        sendMsg(f.channel());
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.github.herong.rpc.netty.protobuf.demo2.Demo2ProtobufServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {// ww  w.  j av a  2 s.c o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(Message.DTO.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new Demo2ProtobufServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(port).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

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 w  w.j a  va2  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.lburgazzoli.quickfixj.transport.netty.NettySocketInitiator.java

License:Apache License

/**
 *
 *//*from www. j  av a 2 s. c  o m*/
private void doConnect() {
    ChannelFuture future = m_boot.connect();
    future.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isDone() && future.isSuccess()) {
                setChannel(new NettyChannel(future.channel()));
            } else if (!future.isSuccess() && !future.isCancelled()) {
                LOGGER.warn("Error", future.cause());
                doReconnect();
            }
        }
    });
}

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 ww  .  j  av  a 2s .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  2 s .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.AbstractKafkaBroker.java

License:Apache License

public ChannelFuture connect() {
    final ChannelFuture channelFuture = bootstrap.connect(hostname, port);
    channel = channelFuture.channel();
    return channelFuture;
}

From source file:com.github.milenkovicm.kafka.KafkaProducer.java

License:Apache License

DataKafkaBroker connectDataChannel(List<ChannelFuture> promises, MetadataResponse.Broker broker) {
    LOGGER.debug("connecting data channel to broker:[{}] hostname: [{}] port:[{}]", broker.nodeId, broker.host,
            broker.port);//  w  ww. j  a  va 2 s  . c  o m
    final DataKafkaBroker channel = new DataKafkaBroker(broker.host, broker.port, broker.nodeId, topicName,
            workerGroup, properties);

    final ChannelFuture future = channel.connect();
    future.channel().closeFuture().addListener(new BrokerDisconnectedListener(channel));
    promises.add(future);
    return channel;
}

From source file:com.github.mrstampy.gameboot.netty.NettyConnectionRegistry.java

License:Open Source License

private void log(ChannelFuture f, Object key) {
    if (f.isSuccess()) {
        log.debug("Successful send to {} on {}", key, f.channel());
    } else {/*from  w w w.ja va2  s .c om*/
        log.error("Failed sending to {} on {}", key, f.channel(), f.cause());
    }
}

From source file:com.github.mrstampy.gameboot.otp.netty.OtpNettyTest.java

License:Open Source License

private void createClearChannel() throws InterruptedException {
    CountDownLatch cdl = new CountDownLatch(1);
    clientHandler.setResponseLatch(cdl);

    ChannelFuture cf = clearClient.connect(HOST, CLEAR_SERVER_PORT);
    cdl.await(5, TimeUnit.SECONDS);

    assertTrue(cf.isSuccess());//w  ww  . j  a v  a2s  .co m
    clearChannel = cf.channel();

    assertNotNull(clientHandler.getSystemId());
    assertEquals(clearChannel, clientHandler.getClearChannel());
}