Search in sources :

Example 6 with ChannelFutureListener

use of io.netty.channel.ChannelFutureListener in project mongo-java-driver by mongodb.

the class NettyStream method writeAsync.

@Override
public void writeAsync(final List<ByteBuf> buffers, final AsyncCompletionHandler<Void> handler) {
    CompositeByteBuf composite = PooledByteBufAllocator.DEFAULT.compositeBuffer();
    for (ByteBuf cur : buffers) {
        composite.addComponent(true, ((NettyByteBuf) cur).asByteBuf());
    }
    channel.writeAndFlush(composite).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                handler.failed(future.cause());
            } else {
                handler.completed(null);
            }
        }
    });
}
Also used : CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ChannelFuture(io.netty.channel.ChannelFuture) ByteBuf(org.bson.ByteBuf) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) MongoInternalException(com.mongodb.MongoInternalException) MongoSocketOpenException(com.mongodb.MongoSocketOpenException) ReadTimeoutException(io.netty.handler.timeout.ReadTimeoutException) MongoInterruptedException(com.mongodb.MongoInterruptedException) MongoException(com.mongodb.MongoException) IOException(java.io.IOException) MongoSocketReadTimeoutException(com.mongodb.MongoSocketReadTimeoutException)

Example 7 with ChannelFutureListener

use of io.netty.channel.ChannelFutureListener in project netty-socketio by mrniko.

the class WebSocketTransport method handshake.

private void handshake(ChannelHandlerContext ctx, final UUID sessionId, String path, FullHttpRequest req) {
    final Channel channel = ctx.channel();
    WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true, configuration.getMaxFramePayloadLength());
    WebSocketServerHandshaker handshaker = factory.newHandshaker(req);
    if (handshaker != null) {
        ChannelFuture f = handshaker.handshake(channel, req);
        f.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    log.error("Can't handshake " + sessionId, future.cause());
                    return;
                }
                channel.pipeline().addBefore(SocketIOChannelInitializer.WEB_SOCKET_TRANSPORT, SocketIOChannelInitializer.WEB_SOCKET_AGGREGATOR, new WebSocketFrameAggregator(configuration.getMaxFramePayloadLength()));
                connectClient(channel, sessionId);
            }
        });
    } else {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) WebSocketFrameAggregator(io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator) WebSocketServerHandshaker(io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker) Channel(io.netty.channel.Channel) WebSocketServerHandshakerFactory(io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 8 with ChannelFutureListener

use of io.netty.channel.ChannelFutureListener in project netty by netty.

the class HexDumpProxyFrontendHandler method channelActive.

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();
    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()).handler(new HexDumpProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(remoteHost, remotePort);
    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 9 with ChannelFutureListener

use of io.netty.channel.ChannelFutureListener in project netty by netty.

the class LocalChannelTest method testWriteWhilePeerIsClosedReleaseObjectAndFailPromise.

@Test
public void testWriteWhilePeerIsClosedReleaseObjectAndFailPromise() throws InterruptedException {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    final CountDownLatch serverMessageLatch = new CountDownLatch(1);
    final LatchChannelFutureListener serverChannelCloseLatch = new LatchChannelFutureListener(1);
    final LatchChannelFutureListener clientChannelCloseLatch = new LatchChannelFutureListener(1);
    final CountDownLatch writeFailLatch = new CountDownLatch(1);
    final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
    final ByteBuf data2 = Unpooled.wrappedBuffer(new byte[512]);
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    final AtomicReference<Channel> serverChannelRef = new AtomicReference<Channel>();
    try {
        cb.group(group1).channel(LocalChannel.class).handler(new TestHandler());
        sb.group(group2).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        if (data.equals(msg)) {
                            ReferenceCountUtil.safeRelease(msg);
                            serverMessageLatch.countDown();
                        } else {
                            super.channelRead(ctx, msg);
                        }
                    }
                });
                serverChannelRef.set(ch);
                serverChannelLatch.countDown();
            }
        });
        Channel sc = null;
        Channel cc = null;
        try {
            // Start server
            sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
            // Connect to the server
            cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
            assertTrue(serverChannelLatch.await(5, SECONDS));
            final Channel ccCpy = cc;
            final Channel serverChannelCpy = serverChannelRef.get();
            serverChannelCpy.closeFuture().addListener(serverChannelCloseLatch);
            ccCpy.closeFuture().addListener(clientChannelCloseLatch);
            // Make sure a write operation is executed in the eventloop
            cc.pipeline().lastContext().executor().execute(new Runnable() {

                @Override
                public void run() {
                    ccCpy.writeAndFlush(data.retainedDuplicate(), ccCpy.newPromise()).addListener(new ChannelFutureListener() {

                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            serverChannelCpy.eventLoop().execute(new Runnable() {

                                @Override
                                public void run() {
                                    // The point of this test is to write while the peer is closed, so we should
                                    // ensure the peer is actually closed before we write.
                                    int waitCount = 0;
                                    while (ccCpy.isOpen()) {
                                        try {
                                            Thread.sleep(50);
                                        } catch (InterruptedException ignored) {
                                        // ignored
                                        }
                                        if (++waitCount > 5) {
                                            fail();
                                        }
                                    }
                                    serverChannelCpy.writeAndFlush(data2.retainedDuplicate(), serverChannelCpy.newPromise()).addListener(new ChannelFutureListener() {

                                        @Override
                                        public void operationComplete(ChannelFuture future) throws Exception {
                                            if (!future.isSuccess() && future.cause() instanceof ClosedChannelException) {
                                                writeFailLatch.countDown();
                                            }
                                        }
                                    });
                                }
                            });
                            ccCpy.close();
                        }
                    });
                }
            });
            assertTrue(serverMessageLatch.await(5, SECONDS));
            assertTrue(writeFailLatch.await(5, SECONDS));
            assertTrue(serverChannelCloseLatch.await(5, SECONDS));
            assertTrue(clientChannelCloseLatch.await(5, SECONDS));
            assertFalse(ccCpy.isOpen());
            assertFalse(serverChannelCpy.isOpen());
        } finally {
            closeChannel(cc);
            closeChannel(sc);
        }
    } finally {
        data.release();
        data2.release();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ClosedChannelException(java.nio.channels.ClosedChannelException) AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 10 with ChannelFutureListener

use of io.netty.channel.ChannelFutureListener in project netty by netty.

the class LocalChannelTest method testClosePeerInWritePromiseCompleteSameEventLoopPreservesOrder.

@Test
public void testClosePeerInWritePromiseCompleteSameEventLoopPreservesOrder() throws InterruptedException {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    final CountDownLatch messageLatch = new CountDownLatch(2);
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
    final AtomicReference<Channel> serverChannelRef = new AtomicReference<Channel>();
    try {
        cb.group(sharedGroup).channel(LocalChannel.class).handler(new TestHandler());
        sb.group(sharedGroup).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        if (msg.equals(data)) {
                            ReferenceCountUtil.safeRelease(msg);
                            messageLatch.countDown();
                        } else {
                            super.channelRead(ctx, msg);
                        }
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        messageLatch.countDown();
                        super.channelInactive(ctx);
                    }
                });
                serverChannelRef.set(ch);
                serverChannelLatch.countDown();
            }
        });
        Channel sc = null;
        Channel cc = null;
        try {
            // Start server
            sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
            // Connect to the server
            cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
            assertTrue(serverChannelLatch.await(5, SECONDS));
            final Channel ccCpy = cc;
            // Make sure a write operation is executed in the eventloop
            cc.pipeline().lastContext().executor().execute(new Runnable() {

                @Override
                public void run() {
                    ChannelPromise promise = ccCpy.newPromise();
                    promise.addListener(new ChannelFutureListener() {

                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            serverChannelRef.get().close();
                        }
                    });
                    ccCpy.writeAndFlush(data.retainedDuplicate(), promise);
                }
            });
            assertTrue(messageLatch.await(5, SECONDS));
            assertFalse(cc.isOpen());
            assertFalse(serverChannelRef.get().isOpen());
        } finally {
            closeChannel(cc);
            closeChannel(sc);
        }
    } finally {
        data.release();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Aggregations

ChannelFutureListener (io.netty.channel.ChannelFutureListener)90 ChannelFuture (io.netty.channel.ChannelFuture)85 Channel (io.netty.channel.Channel)27 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)24 Bootstrap (io.netty.bootstrap.Bootstrap)19 Test (org.junit.Test)19 ByteBuf (io.netty.buffer.ByteBuf)18 ClosedChannelException (java.nio.channels.ClosedChannelException)17 CountDownLatch (java.util.concurrent.CountDownLatch)16 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)15 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)14 IOException (java.io.IOException)12 ChannelPromise (io.netty.channel.ChannelPromise)11 ConnectException (java.net.ConnectException)11 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)10 InetSocketAddress (java.net.InetSocketAddress)7 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 AbstractChannel (io.netty.channel.AbstractChannel)6 EventLoopGroup (io.netty.channel.EventLoopGroup)6 ChannelPipeline (io.netty.channel.ChannelPipeline)4