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.lin.studytest.netty.server.EchoServer.java

License:Apache License

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

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from w  ww . j a va2 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 {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new EchoServerHandler());
                    }
                });

        // 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.linecorp.armeria.client.http.HttpRequestSubscriber.java

License:Apache License

/**
 * Invoked on each write of an {@link HttpObject}.
 *//*  ww w . ja  v a  2s . co m*/
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (future.isSuccess()) {
        if (state != State.DONE) {
            subscription.request(1);
        }
        return;
    }

    fail(future.cause());

    final Throwable cause = future.cause();
    if (!(cause instanceof ClosedPublisherException)) {
        final Channel ch = future.channel();
        Exceptions.logIfUnexpected(logger, ch, HttpSession.get(ch).protocol(), cause);
        ch.close();
    }
}

From source file:com.linecorp.armeria.client.http.HttpSessionChannelFactory.java

License:Apache License

private void initSession(SessionProtocol protocol, ChannelFuture connectFuture,
        Promise<Channel> sessionPromise) {
    assert connectFuture.isSuccess();

    final Channel ch = connectFuture.channel();
    final EventLoop eventLoop = ch.eventLoop();
    assert eventLoop.inEventLoop();

    final ScheduledFuture<?> timeoutFuture = eventLoop.schedule(() -> {
        if (sessionPromise.tryFailure(new SessionProtocolNegotiationException(protocol,
                "connection established, but session creation timed out: " + ch))) {
            ch.close();//from   w  w  w .ja  v  a 2  s.  c o  m
        }
    }, options.connectTimeoutMillis(), TimeUnit.MILLISECONDS);

    ch.pipeline().addLast(new HttpSessionHandler(this, ch, sessionPromise, timeoutFuture));
}

From source file:com.linecorp.armeria.client.HttpRequestSubscriber.java

License:Apache License

/**
 * Invoked on each write of an {@link HttpObject}.
 *///w w w .j  a va  2s.c  om
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (future.isSuccess()) {
        if (state == State.DONE) {
            // Successfully sent the request; schedule the response timeout.
            response.scheduleTimeout(ctx);
        } else {
            assert subscription != null;
            subscription.request(1);
        }
        return;
    }

    fail(future.cause());

    final Throwable cause = future.cause();
    if (!(cause instanceof ClosedPublisherException)) {
        final Channel ch = future.channel();
        Exceptions.logIfUnexpected(logger, ch, HttpSession.get(ch).protocol(), cause);
        ch.close();
    }
}

From source file:com.linecorp.armeria.client.HttpSessionChannelFactory.java

License:Apache License

private void initSession(SessionProtocol protocol, ChannelFuture connectFuture,
        Promise<Channel> sessionPromise) {
    assert connectFuture.isSuccess();

    final Channel ch = connectFuture.channel();
    final EventLoop eventLoop = ch.eventLoop();
    assert eventLoop.inEventLoop();

    final ScheduledFuture<?> timeoutFuture = eventLoop.schedule(() -> {
        if (sessionPromise.tryFailure(new SessionProtocolNegotiationException(protocol,
                "connection established, but session creation timed out: " + ch))) {
            ch.close();//  ww  w.j a  va 2 s . co m
        }
    }, connectTimeoutMillis, TimeUnit.MILLISECONDS);

    ch.pipeline().addLast(new HttpSessionHandler(this, ch, sessionPromise, timeoutFuture));
}

From source file:com.linkedin.mitm.proxy.ProxyServer.java

License:Open Source License

/**
 * Start proxy server/*from   ww  w.  ja  v  a 2 s . c om*/
 * */
public void start() throws InterruptedException {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(_acceptorGroup, _upstreamWorkerGroup);
    serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() {
        @Override
        public ServerChannel newChannel() {
            return new NioServerSocketChannel();
        }
    });
    serverBootstrap.childHandler(new ProxyInitializer(this));

    //bind
    ChannelFuture future = serverBootstrap.bind(_host, _port);

    //wait for the future
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        future.channel().closeFuture().awaitUninterruptibly();
        throw new ChannelException(String.format("Failed to bind to: %s:%d", _host, _port), future.cause());
    } else {
        _allChannels.add(future.channel());
    }
}

From source file:com.linkedin.mitm.proxy.ProxyServer.java

License:Open Source License

/**
 * Stop proxy server//from   w  ww. j a  va  2s.  com
 * */
public void stop() {
    ChannelGroupFuture future = _allChannels.close().awaitUninterruptibly();
    if (!future.isSuccess()) {
        final Iterator<ChannelFuture> iter = future.iterator();
        while (iter.hasNext()) {
            final ChannelFuture cf = iter.next();
            if (!cf.isSuccess()) {
                LOG.warn(String.format("Failed to close channel %s because %s", cf.channel(), cf.cause()));
            }
        }
    }
    _acceptorGroup.shutdownGracefully();
    _upstreamWorkerGroup.shutdownGracefully();
    _downstreamWorkerGroup.shutdownGracefully();
}

From source file:com.linkedin.pinot.transport.netty.NettyServer.java

License:Apache License

@Override
public void run() {
    try {/* w ww.jav a2s  .  c  o m*/
        ServerBootstrap bootstrap = getServerBootstrap();

        LOGGER.info("Binding to the server port !!");

        // Bind and start to accept incoming connections.
        ChannelFuture f = bootstrap.bind(_port).sync();
        _channel = f.channel();
        LOGGER.info("Server bounded to port :" + _port + ", Waiting for closing");
        f.channel().closeFuture().sync();
        LOGGER.info(
                "Server boss channel is closed. Gracefully shutting down the server netty threads and pipelines");
    } catch (Exception e) {
        LOGGER.error("Got exception in the main server thread. Stopping !!", e);
    } finally {
        _shutdownComplete.set(true);
    }
}

From source file:com.linkedin.r2.transport.http.client.ChannelPoolLifecycle.java

License:Apache License

@Override
public void create(final Callback<Channel> channelCallback) {
    final long start = System.currentTimeMillis();
    _bootstrap.connect(_remoteAddress).addListener(new ChannelFutureListener() {
        @Override//w ww .  ja  v a 2  s .c o  m
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                synchronized (_createTimeTracker) {
                    _createTimeTracker.addValue(System.currentTimeMillis() - start);
                }
                Channel c = channelFuture.channel();
                if (_tcpNoDelay) {
                    c.config().setOption(ChannelOption.TCP_NODELAY, true);
                }
                _channelGroup.add(c);
                channelCallback.onSuccess(c);
            } else {
                channelCallback.onError(HttpNettyStreamClient.toException(channelFuture.cause()));
            }
        }
    });
}

From source file:com.linkedin.r2.transport.http.client.ChannelPoolLifecycle.java

License:Apache License

@Override
public void destroy(final Channel channel, final boolean error, final Callback<Channel> channelCallback) {
    if (channel.isOpen()) {
        channel.close().addListener(new ChannelFutureListener() {
            @Override/* w ww  .j av  a2s  .  c  om*/
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    channelCallback.onSuccess(channelFuture.channel());
                } else {
                    channelCallback.onError(HttpNettyStreamClient.toException(channelFuture.cause()));
                }
            }
        });
    } else {
        channelCallback.onSuccess(channel);
    }
}