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.doctor.netty5.example.factorial_algorithm.FactorialClient.java

License:Apache License

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

    try {/*  ww w .  j a  v  a 2s.  c  o  m*/
        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 {/*  www .j av  a2 s  .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   w  w  w .j a  va  2  s .c  o 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.dwarf.netty.guide.factorial.FactorialClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from w  ww  . j  a v a 2  s  .c  o  m
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new FactorialClientInitializer(sslCtx));

        // Make a new connection.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Get the handler instance to retrieve the answer.
        FactorialClientHandler handler = (FactorialClientHandler) f.channel().pipeline().last();

        // Print out the answer.
        System.err.format("Factorial of %,d is: %,d", COUNT, handler.getFactorial());
    } finally {
        group.shutdownGracefully();
    }
}

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

License:MIT License

private HttpSessionChannelContext activateHttpSession(URI uri) throws UnknownHostException {

    ChannelFuture cf = null;
    try {/* www  . ja  v  a2  s.c om*/
        cf = m_bootstrap.connect(new InetSocketAddress(InetAddress.getByName(uri.getHost()), uri.getPort()));

        if (!m_urlDropCounters.containsKey(uri.getHost()))
            m_urlDropCounters.put(uri.getHost(), new LongCounter());

    } catch (UnknownHostException e) {
        LOGGER.error("failed to connect to host" + e.getLocalizedMessage());
        throw e;
    }

    cf.awaitUninterruptibly((getConfig().getConnectionTimeoutInSecs() + 1) * 1000);

    if (!cf.channel().isActive()) {
        return null;
    }

    HttpSessionChannelContext sessionContext = new HttpSessionChannelContext();
    sessionContext.setChannel(cf.channel());
    sessionContext.channelConnected();
    sessionContext.setUri(uri.toString());
    sessionContext.getVirtualQueueMonitor().setMaxQueueBackLog(getConfig().getMaxNettyBacklog());
    sessionContext.setSessionDurationInSecs(getConfig().getMaxSessionDurationInSecs());
    return sessionContext;

}

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

License:MIT License

/**
 * @param ecinfo//from w w w .  j  a va  2 s . com
 * @throws Exception
 */
Channel activateEventConsumerSession(EventConsumerInfo ecinfo, boolean asyncConnect, int numConnections)
        throws Exception {

    if (asyncConnect) {

        createAsyncMultipleConnections(ecinfo, numConnections);

    } else {

        // now we create the configd number of connections

        // Start the client.
        ChannelFuture cf = m_bootstrap.connect(InetAddress.getByName(ecinfo.getAdvertisement().getHostName()),
                ecinfo.getAdvertisement().getListenTcpPort()); // (5)

        cf.awaitUninterruptibly((m_transportConfig.getConnectionTimeoutInSecs() + 1) * 1000);

        if (cf.isSuccess()) {
            ConsumerChannelContext ccc = new ConsumerChannelContext();
            ccc.setChannel(cf.channel());

            ecinfo.setChannelContext(cf.channel(), ccc);
            activateEventConsumer(ecinfo);
        }
    }

    return null;
}

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

License:MIT License

/**
 * @param numConnections//from   w  ww  . j  a va 2s. c  om
 */
private void createAsyncMultipleConnections(EventConsumerInfo ecinfo, int numConnections) {

    for (int i = 0; i < numConnections; i++) {

        ChannelFuture cf = null;
        try {

            cf = m_bootstrap.connect(
                    new InetSocketAddress(InetAddress.getByName(ecinfo.getAdvertisement().getHostName()),
                            ecinfo.getAdvertisement().getListenTcpPort()));
        } catch (UnknownHostException e) {
            LOGGER.error("failed to connect to Host - " + ecinfo.getAdvertisement().getHostName() + " - "
                    + e.getLocalizedMessage());
        }

        final EventConsumerActivationRequest ar = new EventConsumerActivationRequest(this, ecinfo,
                m_transportConfig.getMaxNettyBackLog(), cf.channel()); // not sure if it makes sense to make this final

        if (cf != null)
            cf.addListener(ar);

    }
}

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 {// w  ww.  j a v a  2s. 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.emin.igwmp.skm.core.netty.SocksServer.java

License:Apache License

/**
 * ?socket?//from ww w .j  a v a 2 s  .c om
 * */
public void startServer() {
    mServerBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(mSocksServerInitializer);

    try {
        //            mServerBootstrap.bind(PORT).sync().channel().closeFuture().sync();
        mChannelFuture = mServerBootstrap.bind(PORT).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    final EventLoop loop = future.channel().eventLoop();
                    loop.schedule(new Runnable() {
                        @Override
                        public void run() {
                            startServer();
                        }

                    }, 1L, TimeUnit.SECONDS);

                }
            }
        }).sync();
        mChannelFuture.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
        stopServer();
    }

}

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

License:Apache License

public void run() throws InterruptedException {
    final NioEventLoopGroup workerLoop = new NioEventLoopGroup();
    try (final GracefulShutdown ignored = GracefulShutdown.gracefulShutdown(workerLoop::shutdownGracefully)) {
        final Bootstrap bootstrap = new Bootstrap(); // ServerBootstrap ??????????
        final ChannelFuture future = bootstrap.group(workerLoop) // ??? ????? boss /worker ??????
                .channel(NioSocketChannel.class) // NioServerSocketChannel ???????
                .option(ChannelOption.SO_KEEPALIVE, true) // ???? parent ??????? childOption ????
                .handler(ClientChannelInitializerConfigurer.channelInitializer()).connect(host, port) // bind ????? connect
                .sync();/*from www .jav  a 2  s.  co  m*/
        future.channel().closeFuture().sync();
    }
}