Search in sources :

Example 61 with ChannelInboundHandlerAdapter

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

the class SocketConnectTest method testChannelEventsFiredWhenClosedDirectly.

public void testChannelEventsFiredWhenClosedDirectly(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    final BlockingQueue<Integer> events = new LinkedBlockingQueue<Integer>();
    Channel sc = null;
    Channel cc = null;
    try {
        sb.childHandler(new ChannelInboundHandlerAdapter());
        sc = sb.bind(0).syncUninterruptibly().channel();
        cb.handler(new ChannelInboundHandlerAdapter() {

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                events.add(0);
            }

            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                events.add(1);
            }
        });
        // Connect and directly close again.
        cc = cb.connect(sc.localAddress()).addListener(ChannelFutureListener.CLOSE).syncUninterruptibly().channel();
        assertEquals(0, events.take().intValue());
        assertEquals(1, events.take().intValue());
    } finally {
        if (cc != null) {
            cc.close();
        }
        if (sc != null) {
            sc.close();
        }
    }
}
Also used : Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 62 with ChannelInboundHandlerAdapter

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

the class SocketConnectionAttemptTest method testConnectRefused0.

private static void testConnectRefused0(Bootstrap cb, boolean halfClosure) throws Throwable {
    final Promise<Error> errorPromise = GlobalEventExecutor.INSTANCE.newPromise();
    ChannelHandler handler = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            Channel channel = ctx.channel();
            errorPromise.setFailure(new AssertionError("should have never been called"));
        }
    };
    cb.handler(handler);
    cb.option(ChannelOption.ALLOW_HALF_CLOSURE, halfClosure);
    ChannelFuture future = cb.connect(NetUtil.LOCALHOST, TestUtils.getFreePort()).awaitUninterruptibly();
    assertThat(future.cause(), is(instanceOf(ConnectException.class)));
    assertThat(errorPromise.cause(), is(nullValue()));
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 63 with ChannelInboundHandlerAdapter

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

the class SocketEchoTest method testSimpleEcho0.

private static void testSimpleEcho0(ServerBootstrap sb, Bootstrap cb, boolean additionalExecutor, boolean voidPromise, boolean autoRead) throws Throwable {
    final EchoHandler sh = new EchoHandler(autoRead);
    final EchoHandler ch = new EchoHandler(autoRead);
    if (additionalExecutor) {
        sb.childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel c) throws Exception {
                c.pipeline().addLast(group, sh);
            }
        });
        cb.handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel c) throws Exception {
                c.pipeline().addLast(group, ch);
            }
        });
    } else {
        sb.childHandler(sh);
        sb.handler(new ChannelInboundHandlerAdapter() {

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                cause.printStackTrace();
            }
        });
        cb.handler(ch);
    }
    sb.childOption(ChannelOption.AUTO_READ, autoRead);
    cb.option(ChannelOption.AUTO_READ, autoRead);
    Channel sc = sb.bind().sync().channel();
    Channel cc = cb.connect().sync().channel();
    for (int i = 0; i < data.length; ) {
        int length = Math.min(random.nextInt(1024 * 64), data.length - i);
        ByteBuf buf = Unpooled.wrappedBuffer(data, i, length);
        if (voidPromise) {
            assertEquals(cc.voidPromise(), cc.writeAndFlush(buf, cc.voidPromise()));
        } else {
            assertNotEquals(cc.voidPromise(), cc.writeAndFlush(buf));
        }
        i += length;
    }
    while (ch.counter < data.length) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // Ignore.
        }
    }
    while (sh.counter < data.length) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        // Ignore.
        }
    }
    sh.channel.close().sync();
    ch.channel.close().sync();
    sc.close().sync();
    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
        throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
        throw ch.exception.get();
    }
}
Also used : Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) IOException(java.io.IOException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 64 with ChannelInboundHandlerAdapter

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

the class SocketHalfClosedTest method testAllDataReadAfterHalfClosure.

public void testAllDataReadAfterHalfClosure(final boolean autoRead, ServerBootstrap sb, Bootstrap cb) throws Throwable {
    final int totalServerBytesWritten = 1024 * 16;
    final int numReadsPerReadLoop = 2;
    final CountDownLatch serverInitializedLatch = new CountDownLatch(1);
    final CountDownLatch clientReadAllDataLatch = new CountDownLatch(1);
    final CountDownLatch clientHalfClosedLatch = new CountDownLatch(1);
    final AtomicInteger clientReadCompletes = new AtomicInteger();
    Channel serverChannel = null;
    Channel clientChannel = null;
    try {
        cb.option(ChannelOption.ALLOW_HALF_CLOSURE, true).option(ChannelOption.AUTO_READ, autoRead).option(ChannelOption.RCVBUF_ALLOCATOR, new TestNumReadsRecvByteBufAllocator(numReadsPerReadLoop));
        sb.childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        ByteBuf buf = ctx.alloc().buffer(totalServerBytesWritten);
                        buf.writerIndex(buf.capacity());
                        ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                ((DuplexChannel) future.channel()).shutdownOutput();
                            }
                        });
                        serverInitializedLatch.countDown();
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        ctx.close();
                    }
                });
            }
        });
        cb.handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    private int bytesRead;

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) {
                        ByteBuf buf = (ByteBuf) msg;
                        bytesRead += buf.readableBytes();
                        buf.release();
                    }

                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                        if (evt == ChannelInputShutdownEvent.INSTANCE) {
                            clientHalfClosedLatch.countDown();
                        } else if (evt == ChannelInputShutdownReadComplete.INSTANCE) {
                            ctx.close();
                        }
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) {
                        clientReadCompletes.incrementAndGet();
                        if (bytesRead == totalServerBytesWritten) {
                            clientReadAllDataLatch.countDown();
                        }
                        if (!autoRead) {
                            ctx.read();
                        }
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        ctx.close();
                    }
                });
            }
        });
        serverChannel = sb.bind().sync().channel();
        clientChannel = cb.connect(serverChannel.localAddress()).sync().channel();
        clientChannel.read();
        serverInitializedLatch.await();
        clientReadAllDataLatch.await();
        clientHalfClosedLatch.await();
        assertTrue("too many read complete events: " + clientReadCompletes.get(), totalServerBytesWritten / numReadsPerReadLoop + 10 > clientReadCompletes.get());
    } finally {
        if (clientChannel != null) {
            clientChannel.close().sync();
        }
        if (serverChannel != null) {
            serverChannel.close().sync();
        }
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) DuplexChannel(io.netty.channel.socket.DuplexChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 65 with ChannelInboundHandlerAdapter

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

the class SocketMultipleConnectTest method testMultipleConnect.

public void testMultipleConnect(ServerBootstrap sb, Bootstrap cb) throws Exception {
    Channel sc = null;
    Channel cc = null;
    try {
        sb.childHandler(new ChannelInboundHandlerAdapter());
        sc = sb.bind(0).syncUninterruptibly().channel();
        cb.handler(new ChannelInboundHandlerAdapter());
        cc = cb.register().syncUninterruptibly().channel();
        cc.connect(sc.localAddress()).syncUninterruptibly();
        ChannelFuture connectFuture2 = cc.connect(sc.localAddress()).await();
        assertTrue(connectFuture2.cause() instanceof AlreadyConnectedException);
    } finally {
        if (cc != null) {
            cc.close();
        }
        if (sc != null) {
            sc.close();
        }
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AlreadyConnectedException(java.nio.channels.AlreadyConnectedException) Channel(io.netty.channel.Channel) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Aggregations

ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)103 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)75 Channel (io.netty.channel.Channel)65 Test (org.junit.Test)62 Bootstrap (io.netty.bootstrap.Bootstrap)51 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)48 ChannelFuture (io.netty.channel.ChannelFuture)33 CountDownLatch (java.util.concurrent.CountDownLatch)32 EventLoopGroup (io.netty.channel.EventLoopGroup)28 InetSocketAddress (java.net.InetSocketAddress)26 ClosedChannelException (java.nio.channels.ClosedChannelException)26 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)23 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)23 ByteBuf (io.netty.buffer.ByteBuf)22 ChannelFutureListener (io.netty.channel.ChannelFutureListener)17 LocalServerChannel (io.netty.channel.local.LocalServerChannel)17 SocketChannel (io.netty.channel.socket.SocketChannel)17 LocalAddress (io.netty.channel.local.LocalAddress)16 LocalChannel (io.netty.channel.local.LocalChannel)16 AtomicReference (java.util.concurrent.atomic.AtomicReference)15