Search in sources :

Example 11 with ChannelFutureListener

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

the class NioSocketChannelTest method testChannelReRegisterRead.

private static void testChannelReRegisterRead(final boolean sameEventLoop) throws Exception {
    final EventLoopGroup group = new NioEventLoopGroup(2);
    final CountDownLatch latch = new CountDownLatch(1);
    // Just some random bytes
    byte[] bytes = new byte[1024];
    PlatformDependent.threadLocalRandom().nextBytes(bytes);
    Channel sc = null;
    Channel cc = null;
    ServerBootstrap b = new ServerBootstrap();
    try {
        b.group(group).channel(NioServerSocketChannel.class).childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) {
                        // We was able to read something from the Channel after reregister.
                        latch.countDown();
                    }

                    @Override
                    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                        final EventLoop loop = group.next();
                        if (sameEventLoop) {
                            deregister(ctx, loop);
                        } else {
                            loop.execute(new Runnable() {

                                @Override
                                public void run() {
                                    deregister(ctx, loop);
                                }
                            });
                        }
                    }

                    private void deregister(ChannelHandlerContext ctx, final EventLoop loop) {
                        // As soon as the channel becomes active re-register it to another
                        // EventLoop. After this is done we should still receive the data that
                        // was written to the channel.
                        ctx.deregister().addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture cf) {
                                Channel channel = cf.channel();
                                assertNotSame(loop, channel.eventLoop());
                                group.next().register(channel);
                            }
                        });
                    }
                });
            }
        });
        sc = b.bind(0).syncUninterruptibly().channel();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInboundHandlerAdapter());
        cc = bootstrap.connect(sc.localAddress()).syncUninterruptibly().channel();
        cc.writeAndFlush(Unpooled.wrappedBuffer(bytes)).syncUninterruptibly();
        latch.await();
    } finally {
        if (cc != null) {
            cc.close();
        }
        if (sc != null) {
            sc.close();
        }
        group.shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) 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) ClosedChannelException(java.nio.channels.ClosedChannelException) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 12 with ChannelFutureListener

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

the class NioSocketChannelTest method testFlushAfterGatheredFlush.

/**
     * Reproduces the issue #1679
     */
@Test
public void testFlushAfterGatheredFlush() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInboundHandlerAdapter() {

            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                // Trigger a gathering write by writing two buffers.
                ctx.write(Unpooled.wrappedBuffer(new byte[] { 'a' }));
                ChannelFuture f = ctx.write(Unpooled.wrappedBuffer(new byte[] { 'b' }));
                f.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // This message must be flushed
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'c' }));
                    }
                });
                ctx.flush();
            }
        });
        SocketAddress address = sb.bind(0).sync().channel().localAddress();
        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());
        DataInput in = new DataInputStream(s.getInputStream());
        byte[] buf = new byte[3];
        in.readFully(buf);
        assertThat(new String(buf, CharsetUtil.US_ASCII), is("abc"));
        s.close();
    } finally {
        group.shutdownGracefully().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DataInputStream(java.io.DataInputStream) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) DataInput(java.io.DataInput) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Socket(java.net.Socket) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 13 with ChannelFutureListener

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

the class OioEventLoopTest method testTooManyServerChannels.

@Test
public void testTooManyServerChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap b = new ServerBootstrap();
    b.channel(OioServerSocketChannel.class);
    b.group(g);
    b.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = b.bind(0);
    f1.sync();
    ChannelFuture f2 = b.bind(0);
    f2.await();
    assertThat(f2.cause(), is(instanceOf(ChannelException.class)));
    assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels"));
    final CountDownLatch notified = new CountDownLatch(1);
    f2.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            notified.countDown();
        }
    });
    notified.await();
    g.shutdownGracefully();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) EventLoopGroup(io.netty.channel.EventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelException(io.netty.channel.ChannelException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 14 with ChannelFutureListener

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

the class EmbeddedChannelTest method promiseDoesNotInfiniteLoop.

@Test(timeout = 2000)
public void promiseDoesNotInfiniteLoop() throws InterruptedException {
    EmbeddedChannel channel = new EmbeddedChannel();
    channel.closeFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            future.channel().close();
        }
    });
    channel.close().syncUninterruptibly();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ClosedChannelException(java.nio.channels.ClosedChannelException) Test(org.junit.Test)

Example 15 with ChannelFutureListener

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

the class LocalChannelTest method testWriteInWritePromiseCompletePreservesOrder.

@Test
public void testWriteInWritePromiseCompletePreservesOrder() throws InterruptedException {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    final CountDownLatch messageLatch = new CountDownLatch(2);
    final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
    final ByteBuf data2 = Unpooled.wrappedBuffer(new byte[512]);
    try {
        cb.group(group1).channel(LocalChannel.class).handler(new TestHandler());
        sb.group(group2).channel(LocalServerChannel.class).childHandler(new ChannelInboundHandlerAdapter() {

            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                final long count = messageLatch.getCount();
                if ((data.equals(msg) && count == 2) || (data2.equals(msg) && count == 1)) {
                    ReferenceCountUtil.safeRelease(msg);
                    messageLatch.countDown();
                } else {
                    super.channelRead(ctx, msg);
                }
            }
        });
        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();
            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 {
                            ccCpy.writeAndFlush(data2.retainedDuplicate(), ccCpy.newPromise());
                        }
                    });
                    ccCpy.writeAndFlush(data.retainedDuplicate(), promise);
                }
            });
            assertTrue(messageLatch.await(5, SECONDS));
        } finally {
            closeChannel(cc);
            closeChannel(sc);
        }
    } finally {
        data.release();
        data2.release();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) 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