Search in sources :

Example 26 with FutureListener

use of io.netty.util.concurrent.FutureListener in project netty by netty.

the class DefaultHttp2ConnectionTest method removeAllStreamsWhileIteratingActiveStreams.

@Test
public void removeAllStreamsWhileIteratingActiveStreams() throws Exception {
    final Endpoint<Http2RemoteFlowController> remote = client.remote();
    final Endpoint<Http2LocalFlowController> local = client.local();
    for (int c = 3, s = 2; c < 5000; c += 2, s += 2) {
        local.createStream(c, false);
        remote.createStream(s, false);
    }
    final Promise<Void> promise = group.next().newPromise();
    final CountDownLatch latch = new CountDownLatch(client.numActiveStreams());
    client.forEachActiveStream(new Http2StreamVisitor() {

        @Override
        public boolean visit(Http2Stream stream) {
            client.close(promise).addListener(new FutureListener<Void>() {

                @Override
                public void operationComplete(Future<Void> future) throws Exception {
                    assertTrue(promise.isDone());
                    latch.countDown();
                }
            });
            return true;
        }
    });
    assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) CountDownLatch(java.util.concurrent.CountDownLatch) Endpoint(io.netty.handler.codec.http2.Http2Connection.Endpoint) Future(io.netty.util.concurrent.Future) Test(org.junit.jupiter.api.Test)

Example 27 with FutureListener

use of io.netty.util.concurrent.FutureListener in project netty by netty.

the class SocksServerConnectHandler method channelRead0.

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {

            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));
                    responseFuture.addListener(new ChannelFutureListener() {

                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true).handler(new DirectClientHandler(promise));
        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {

            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS, request.dstAddrType(), request.dstAddr(), request.dstPort()));
                    responseFuture.addListener(new ChannelFutureListener() {

                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true).handler(new DirectClientHandler(promise));
        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Socks5CommandRequest(io.netty.handler.codec.socksx.v5.Socks5CommandRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelFutureListener(io.netty.channel.ChannelFutureListener) DefaultSocks5CommandResponse(io.netty.handler.codec.socksx.v5.DefaultSocks5CommandResponse) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Promise(io.netty.util.concurrent.Promise) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) Socks4CommandRequest(io.netty.handler.codec.socksx.v4.Socks4CommandRequest) DefaultSocks4CommandResponse(io.netty.handler.codec.socksx.v4.DefaultSocks4CommandResponse)

Example 28 with FutureListener

use of io.netty.util.concurrent.FutureListener in project netty by netty.

the class ParameterizedSslHandlerTest method testCloseNotify.

private void testCloseNotify(SslProvider clientProvider, SslProvider serverProvider, final long closeNotifyReadTimeout, final boolean timeout) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(serverProvider).protocols(SslProtocols.TLS_v1_2).build();
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(clientProvider).protocols(SslProtocols.TLS_v1_2).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    try {
        final Promise<Channel> clientPromise = group.next().newPromise();
        final Promise<Channel> serverPromise = group.next().newPromise();
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                SslHandler handler = sslServerCtx.newHandler(ch.alloc());
                handler.setCloseNotifyReadTimeoutMillis(closeNotifyReadTimeout);
                PromiseNotifier.cascade(handler.sslCloseFuture(), serverPromise);
                handler.handshakeFuture().addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) {
                        if (!future.isSuccess()) {
                            // Something bad happened during handshake fail the promise!
                            serverPromise.tryFailure(future.cause());
                        }
                    }
                });
                ch.pipeline().addLast(handler);
            }
        }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        cc = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                final AtomicBoolean closeSent = new AtomicBoolean();
                if (timeout) {
                    ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() {

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (closeSent.get()) {
                                // Drop data on the floor so we will get a timeout while waiting for the
                                // close_notify.
                                ReferenceCountUtil.release(msg);
                            } else {
                                super.channelRead(ctx, msg);
                            }
                        }
                    });
                }
                SslHandler handler = sslClientCtx.newHandler(ch.alloc());
                handler.setCloseNotifyReadTimeoutMillis(closeNotifyReadTimeout);
                PromiseNotifier.cascade(handler.sslCloseFuture(), clientPromise);
                handler.handshakeFuture().addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(Future<Channel> future) {
                        if (future.isSuccess()) {
                            closeSent.compareAndSet(false, true);
                            future.getNow().close();
                        } else {
                            // Something bad happened during handshake fail the promise!
                            clientPromise.tryFailure(future.cause());
                        }
                    }
                });
                ch.pipeline().addLast(handler);
            }
        }).connect(sc.localAddress()).syncUninterruptibly().channel();
        serverPromise.awaitUninterruptibly();
        clientPromise.awaitUninterruptibly();
        // Server always received the close_notify as the client triggers the close sequence.
        assertTrue(serverPromise.isSuccess());
        // Depending on if we wait for the response or not the promise will be failed or not.
        if (closeNotifyReadTimeout > 0 && !timeout) {
            assertTrue(clientPromise.isSuccess());
        } else {
            assertFalse(clientPromise.isSuccess());
        }
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslServerCtx);
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SSLException(javax.net.ssl.SSLException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 29 with FutureListener

use of io.netty.util.concurrent.FutureListener in project netty by netty.

the class EmbeddedChannelTest method testScheduling.

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testScheduling() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
    final CountDownLatch latch = new CountDownLatch(2);
    Future future = ch.eventLoop().schedule(new Runnable() {

        @Override
        public void run() {
            latch.countDown();
        }
    }, 1, TimeUnit.SECONDS);
    future.addListener(new FutureListener() {

        @Override
        public void operationComplete(Future future) throws Exception {
            latch.countDown();
        }
    });
    long next = ch.runScheduledPendingTasks();
    assertTrue(next > 0);
    // Sleep for the nanoseconds but also give extra 50ms as the clock my not be very precise and so fail the test
    // otherwise.
    Thread.sleep(TimeUnit.NANOSECONDS.toMillis(next) + 50);
    assertEquals(-1, ch.runScheduledPendingTasks());
    latch.await();
}
Also used : ChannelFutureListener(io.netty.channel.ChannelFutureListener) FutureListener(io.netty.util.concurrent.FutureListener) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) CountDownLatch(java.util.concurrent.CountDownLatch) ClosedChannelException(java.nio.channels.ClosedChannelException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Aggregations

FutureListener (io.netty.util.concurrent.FutureListener)29 Future (io.netty.util.concurrent.Future)26 RFuture (org.redisson.api.RFuture)20 ChannelFuture (io.netty.channel.ChannelFuture)10 ChannelFutureListener (io.netty.channel.ChannelFutureListener)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 Timeout (io.netty.util.Timeout)6 TimerTask (io.netty.util.TimerTask)6 ArrayList (java.util.ArrayList)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 RedisConnection (org.redisson.client.RedisConnection)6 Channel (io.netty.channel.Channel)4 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)4 ScheduledFuture (io.netty.util.concurrent.ScheduledFuture)4 Test (org.junit.jupiter.api.Test)4 RedisConnectionException (org.redisson.client.RedisConnectionException)4 RedisException (org.redisson.client.RedisException)4 NodeSource (org.redisson.connection.NodeSource)4