Search in sources :

Example 31 with Bootstrap

use of io.netty.bootstrap.Bootstrap 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)

Example 32 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project netty by netty.

the class ReentrantChannelTest method testCloseInFlush.

@Test
public void testCloseInFlush() throws Exception {
    LocalAddress addr = new LocalAddress("testCloseInFlush");
    ServerBootstrap sb = getLocalServerBootstrap();
    sb.bind(addr).sync().channel();
    Bootstrap cb = getLocalClientBootstrap();
    setInterest(Event.WRITE, Event.FLUSH, Event.CLOSE, Event.EXCEPTION);
    Channel clientChannel = cb.connect(addr).sync().channel();
    clientChannel.pipeline().addLast(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            promise.addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    ctx.channel().close();
                }
            });
            super.write(ctx, msg, promise);
            ctx.channel().flush();
        }
    });
    clientChannel.write(createTestBuf(2000)).sync();
    clientChannel.closeFuture().sync();
    assertLog("WRITE\nFLUSH\nCLOSE\n");
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Future(io.netty.util.concurrent.Future) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Test(org.junit.Test)

Example 33 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project netty by netty.

the class ReentrantChannelTest method testWritabilityChanged.

@Test
public void testWritabilityChanged() throws Exception {
    LocalAddress addr = new LocalAddress("testWritabilityChanged");
    ServerBootstrap sb = getLocalServerBootstrap();
    sb.bind(addr).sync().channel();
    Bootstrap cb = getLocalClientBootstrap();
    setInterest(Event.WRITE, Event.FLUSH, Event.WRITABILITY);
    Channel clientChannel = cb.connect(addr).sync().channel();
    clientChannel.config().setWriteBufferLowWaterMark(512);
    clientChannel.config().setWriteBufferHighWaterMark(1024);
    // What is supposed to happen from this point:
    //
    // 1. Because this write attempt has been made from a non-I/O thread,
    //    ChannelOutboundBuffer.pendingWriteBytes will be increased before
    //    write() event is really evaluated.
    //    -> channelWritabilityChanged() will be triggered,
    //       because the Channel became unwritable.
    //
    // 2. The write() event is handled by the pipeline in an I/O thread.
    //    -> write() will be triggered.
    //
    // 3. Once the write() event is handled, ChannelOutboundBuffer.pendingWriteBytes
    //    will be decreased.
    //    -> channelWritabilityChanged() will be triggered,
    //       because the Channel became writable again.
    //
    // 4. The message is added to the ChannelOutboundBuffer and thus
    //    pendingWriteBytes will be increased again.
    //    -> channelWritabilityChanged() will be triggered.
    //
    // 5. The flush() event causes the write request in theChannelOutboundBuffer
    //    to be removed.
    //    -> flush() and channelWritabilityChanged() will be triggered.
    //
    // Note that the channelWritabilityChanged() in the step 4 can occur between
    // the flush() and the channelWritabilityChanged() in the stap 5, because
    // the flush() is invoked from a non-I/O thread while the other are from
    // an I/O thread.
    ChannelFuture future = clientChannel.write(createTestBuf(2000));
    clientChannel.flush();
    future.sync();
    clientChannel.close().sync();
    assertLog(// Case 1:
    "WRITABILITY: writable=false\n" + "WRITE\n" + "WRITABILITY: writable=false\n" + "WRITABILITY: writable=false\n" + "FLUSH\n" + "WRITABILITY: writable=true\n", // Case 2:
    "WRITABILITY: writable=false\n" + "WRITE\n" + "WRITABILITY: writable=false\n" + "FLUSH\n" + "WRITABILITY: writable=true\n" + "WRITABILITY: writable=true\n");
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Test(org.junit.Test)

Example 34 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project netty by netty.

the class SimpleChannelPoolTest method testAcquire.

@Test
public void testAcquire() throws Exception {
    EventLoopGroup group = new LocalEventLoopGroup();
    LocalAddress addr = new LocalAddress(LOCAL_ADDR_ID);
    Bootstrap cb = new Bootstrap();
    cb.remoteAddress(addr);
    cb.group(group).channel(LocalChannel.class);
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter());
        }
    });
    // Start server
    Channel sc = sb.bind(addr).sync().channel();
    CountingChannelPoolHandler handler = new CountingChannelPoolHandler();
    ChannelPool pool = new SimpleChannelPool(cb, handler);
    Channel channel = pool.acquire().sync().getNow();
    pool.release(channel).syncUninterruptibly();
    Channel channel2 = pool.acquire().sync().getNow();
    assertSame(channel, channel2);
    assertEquals(1, handler.channelCount());
    pool.release(channel2).syncUninterruptibly();
    // Should fail on multiple release calls.
    try {
        pool.release(channel2).syncUninterruptibly();
        fail();
    } catch (IllegalArgumentException e) {
        // expected
        assertFalse(channel.isActive());
    }
    assertEquals(1, handler.acquiredCount());
    assertEquals(2, handler.releasedCount());
    sc.close().sync();
    group.shutdownGracefully();
}
Also used : LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ExpectedException(org.junit.rules.ExpectedException) EventLoopGroup(io.netty.channel.EventLoopGroup) LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 35 with Bootstrap

use of io.netty.bootstrap.Bootstrap in project netty by netty.

the class SimpleChannelPoolTest method testUnhealthyChannelIsOfferedWhenNoHealthCheckRequested.

/**
     * Tests that if channel was unhealthy it is was offered back to the pool because
     * it was requested not to validate channel health on release.
     *
     * @throws Exception
     */
@Test
public void testUnhealthyChannelIsOfferedWhenNoHealthCheckRequested() throws Exception {
    EventLoopGroup group = new LocalEventLoopGroup();
    LocalAddress addr = new LocalAddress(LOCAL_ADDR_ID);
    Bootstrap cb = new Bootstrap();
    cb.remoteAddress(addr);
    cb.group(group).channel(LocalChannel.class);
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter());
        }
    });
    // Start server
    Channel sc = sb.bind(addr).syncUninterruptibly().channel();
    ChannelPoolHandler handler = new CountingChannelPoolHandler();
    ChannelPool pool = new SimpleChannelPool(cb, handler, ChannelHealthChecker.ACTIVE, false);
    Channel channel1 = pool.acquire().syncUninterruptibly().getNow();
    channel1.close().syncUninterruptibly();
    Future<Void> releaseFuture = pool.release(channel1, channel1.eventLoop().<Void>newPromise()).syncUninterruptibly();
    assertThat(releaseFuture.isSuccess(), CoreMatchers.is(true));
    Channel channel2 = pool.acquire().syncUninterruptibly().getNow();
    //verifying that in fact the channel2 is different that means is not pulled from the pool
    assertNotSame(channel1, channel2);
    sc.close().syncUninterruptibly();
    channel2.close().syncUninterruptibly();
    group.shutdownGracefully();
}
Also used : LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ExpectedException(org.junit.rules.ExpectedException) EventLoopGroup(io.netty.channel.EventLoopGroup) LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)163 Channel (io.netty.channel.Channel)81 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)73 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)68 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)68 ChannelFuture (io.netty.channel.ChannelFuture)62 EventLoopGroup (io.netty.channel.EventLoopGroup)61 Test (org.junit.Test)61 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)49 InetSocketAddress (java.net.InetSocketAddress)49 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)37 SocketChannel (io.netty.channel.socket.SocketChannel)33 ChannelPipeline (io.netty.channel.ChannelPipeline)31 LocalAddress (io.netty.channel.local.LocalAddress)26 ClosedChannelException (java.nio.channels.ClosedChannelException)26 LocalChannel (io.netty.channel.local.LocalChannel)22 LocalServerChannel (io.netty.channel.local.LocalServerChannel)22 CountDownLatch (java.util.concurrent.CountDownLatch)22 ChannelFutureListener (io.netty.channel.ChannelFutureListener)20 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)18