Search in sources :

Example 6 with ChannelFuture

use of io.netty.channel.ChannelFuture in project hive by apache.

the class Rpc method createClient.

/**
   * Creates an RPC client for a server running on the given remote host and port.
   *
   * @param config RPC configuration data.
   * @param eloop Event loop for managing the connection.
   * @param host Host name or IP address to connect to.
   * @param port Port where server is listening.
   * @param clientId The client ID that identifies the connection.
   * @param secret Secret for authenticating the client with the server.
   * @param dispatcher Dispatcher used to handle RPC calls.
   * @return A future that can be used to monitor the creation of the RPC object.
   */
public static Promise<Rpc> createClient(Map<String, String> config, final NioEventLoopGroup eloop, String host, int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    final RpcConfiguration rpcConf = new RpcConfiguration(config);
    int connectTimeoutMs = (int) rpcConf.getConnectTimeoutMs();
    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);
    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();
    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {

        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask, connectTimeoutMs, TimeUnit.MILLISECONDS);
    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(rpcConf, clientId, promise, timeoutFuture, secret, dispatcher);
                Rpc rpc = createRpc(rpcConf, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });
    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {

        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });
    return promise;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelFutureListener(io.netty.channel.ChannelFutureListener) TimeoutException(java.util.concurrent.TimeoutException) SaslException(javax.security.sasl.SaslException) IOException(java.io.IOException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Promise(io.netty.util.concurrent.Promise) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) TimeoutException(java.util.concurrent.TimeoutException)

Example 7 with ChannelFuture

use of io.netty.channel.ChannelFuture in project moco by dreamhead.

the class MocoClient method run.

public void run(final String host, final int port, final ChannelHandler pipelineFactory) {
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).remoteAddress(host, port).option(ChannelOption.TCP_NODELAY, true).handler(pipelineFactory);
    try {
        Channel channel = bootstrap.connect().sync().channel();
        ChannelFuture future = channel.closeFuture().sync();
        future.addListener(ChannelFutureListener.CLOSE);
    } catch (InterruptedException e) {
        throw new MocoException(e);
    } finally {
        group.shutdownGracefully();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChannelFuture(io.netty.channel.ChannelFuture) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Channel(io.netty.channel.Channel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) MocoException(com.github.dreamhead.moco.MocoException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 8 with ChannelFuture

use of io.netty.channel.ChannelFuture in project elasticsearch by elastic.

the class Netty4Utils method closeChannels.

public static void closeChannels(final Collection<Channel> channels) throws IOException {
    IOException closingExceptions = null;
    final List<ChannelFuture> futures = new ArrayList<>();
    for (final Channel channel : channels) {
        try {
            if (channel != null && channel.isOpen()) {
                futures.add(channel.close());
            }
        } catch (Exception e) {
            if (closingExceptions == null) {
                closingExceptions = new IOException("failed to close channels");
            }
            closingExceptions.addSuppressed(e);
        }
    }
    for (final ChannelFuture future : futures) {
        future.awaitUninterruptibly();
    }
    if (closingExceptions != null) {
        throw closingExceptions;
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IOException(java.io.IOException)

Example 9 with ChannelFuture

use of io.netty.channel.ChannelFuture in project elasticsearch by elastic.

the class Netty4HttpClient method sendRequests.

private synchronized Collection<FullHttpResponse> sendRequests(final SocketAddress remoteAddress, final Collection<HttpRequest> requests) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(requests.size());
    final Collection<FullHttpResponse> content = Collections.synchronizedList(new ArrayList<>(requests.size()));
    clientBootstrap.handler(new CountDownLatchHandler(latch, content));
    ChannelFuture channelFuture = null;
    try {
        channelFuture = clientBootstrap.connect(remoteAddress);
        channelFuture.sync();
        for (HttpRequest request : requests) {
            channelFuture.channel().writeAndFlush(request);
        }
        latch.await(10, TimeUnit.SECONDS);
    } finally {
        if (channelFuture != null) {
            channelFuture.channel().close().sync();
        }
    }
    return content;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 10 with ChannelFuture

use of io.netty.channel.ChannelFuture in project vert.x by eclipse.

the class DatagramSocketImpl method doSend.

private void doSend(Buffer packet, InetSocketAddress addr, Handler<AsyncResult<DatagramSocket>> handler) {
    ChannelFuture future = channel().writeAndFlush(new DatagramPacket(packet.getByteBuf(), addr));
    addListener(future, handler);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DatagramPacket(io.netty.channel.socket.DatagramPacket)

Aggregations

ChannelFuture (io.netty.channel.ChannelFuture)361 Test (org.junit.Test)128 Channel (io.netty.channel.Channel)114 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)102 Bootstrap (io.netty.bootstrap.Bootstrap)93 ChannelFutureListener (io.netty.channel.ChannelFutureListener)86 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)86 ByteBuf (io.netty.buffer.ByteBuf)81 InetSocketAddress (java.net.InetSocketAddress)78 EventLoopGroup (io.netty.channel.EventLoopGroup)71 IOException (java.io.IOException)69 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)68 ChannelPipeline (io.netty.channel.ChannelPipeline)63 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)59 ClosedChannelException (java.nio.channels.ClosedChannelException)56 AtomicReference (java.util.concurrent.atomic.AtomicReference)47 ArrayList (java.util.ArrayList)46 ChannelInitializer (io.netty.channel.ChannelInitializer)45 Http2Headers (io.netty.handler.codec.http2.Http2Headers)44 SslHandler (io.netty.handler.ssl.SslHandler)44