Search in sources :

Example 71 with ChannelHandlerContext

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

the class SocketHalfClosedTest method testAllDataReadClosure.

public void testAllDataReadClosure(final boolean autoRead, final boolean allowHalfClosed, 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, allowHalfClosed).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(ChannelFutureListener.CLOSE);
                        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 && allowHalfClosed) {
                            clientHalfClosedLatch.countDown();
                        } else if (evt == ChannelInputShutdownReadComplete.INSTANCE) {
                            ctx.close();
                        }
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) {
                        if (!allowHalfClosed) {
                            clientHalfClosedLatch.countDown();
                        }
                    }

                    @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 : 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) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 72 with ChannelHandlerContext

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

the class WebSocketClientHandshakerTest method testHttpResponseAndFrameInSameBuffer.

private void testHttpResponseAndFrameInSameBuffer(boolean codec) {
    String url = "ws://localhost:9999/ws";
    final WebSocketClientHandshaker shaker = newHandshaker(URI.create(url));
    final WebSocketClientHandshaker handshaker = new WebSocketClientHandshaker(shaker.uri(), shaker.version(), null, EmptyHttpHeaders.INSTANCE, Integer.MAX_VALUE) {

        @Override
        protected FullHttpRequest newHandshakeRequest() {
            return shaker.newHandshakeRequest();
        }

        @Override
        protected void verify(FullHttpResponse response) {
        // Not do any verification, so we not need to care sending the correct headers etc in the test,
        // which would just make things more complicated.
        }

        @Override
        protected WebSocketFrameDecoder newWebsocketDecoder() {
            return shaker.newWebsocketDecoder();
        }

        @Override
        protected WebSocketFrameEncoder newWebSocketEncoder() {
            return shaker.newWebSocketEncoder();
        }
    };
    byte[] data = new byte[24];
    PlatformDependent.threadLocalRandom().nextBytes(data);
    // Create a EmbeddedChannel which we will use to encode a BinaryWebsocketFrame to bytes and so use these
    // to test the actual handshaker.
    WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(url, null, false);
    WebSocketServerHandshaker socketServerHandshaker = factory.newHandshaker(shaker.newHandshakeRequest());
    EmbeddedChannel websocketChannel = new EmbeddedChannel(socketServerHandshaker.newWebSocketEncoder(), socketServerHandshaker.newWebsocketDecoder());
    assertTrue(websocketChannel.writeOutbound(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(data))));
    byte[] bytes = "HTTP/1.1 101 Switching Protocols\r\nContent-Length: 0\r\n\r\n".getBytes(CharsetUtil.US_ASCII);
    CompositeByteBuf compositeByteBuf = Unpooled.compositeBuffer();
    compositeByteBuf.addComponent(true, Unpooled.wrappedBuffer(bytes));
    for (; ; ) {
        ByteBuf frameBytes = websocketChannel.readOutbound();
        if (frameBytes == null) {
            break;
        }
        compositeByteBuf.addComponent(true, frameBytes);
    }
    EmbeddedChannel ch = new EmbeddedChannel(new HttpObjectAggregator(Integer.MAX_VALUE), new SimpleChannelInboundHandler<FullHttpResponse>() {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
            handshaker.finishHandshake(ctx.channel(), msg);
            ctx.pipeline().remove(this);
        }
    });
    if (codec) {
        ch.pipeline().addFirst(new HttpClientCodec());
    } else {
        ch.pipeline().addFirst(new HttpRequestEncoder(), new HttpResponseDecoder());
    }
    // We need to first write the request as HttpClientCodec will fail if we receive a response before a request
    // was written.
    shaker.handshake(ch).syncUninterruptibly();
    for (; ; ) {
        // Just consume the bytes, we are not interested in these.
        ByteBuf buf = ch.readOutbound();
        if (buf == null) {
            break;
        }
        buf.release();
    }
    assertTrue(ch.writeInbound(compositeByteBuf));
    assertTrue(ch.finish());
    BinaryWebSocketFrame frame = ch.readInbound();
    ByteBuf expect = Unpooled.wrappedBuffer(data);
    try {
        assertEquals(expect, frame.content());
        assertTrue(frame.isFinalFragment());
        assertEquals(0, frame.rsv());
    } finally {
        expect.release();
        frame.release();
    }
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) HttpRequestEncoder(io.netty.handler.codec.http.HttpRequestEncoder) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) HttpResponseDecoder(io.netty.handler.codec.http.HttpResponseDecoder)

Example 73 with ChannelHandlerContext

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

the class WebSocket08FrameDecoderTest method channelInactive.

@Test
public void channelInactive() throws Exception {
    final WebSocket08FrameDecoder decoder = new WebSocket08FrameDecoder(true, true, 65535, false);
    final ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class);
    decoder.channelInactive(ctx);
    Mockito.verify(ctx).fireChannelInactive();
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Test(org.junit.Test)

Example 74 with ChannelHandlerContext

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

the class WebSocketServerProtocolHandlerTest method testHttpUpgradeRequest.

@Test
public void testHttpUpgradeRequest() throws Exception {
    EmbeddedChannel ch = createChannel(new MockOutboundHandler());
    ChannelHandlerContext handshakerCtx = ch.pipeline().context(WebSocketServerProtocolHandshakeHandler.class);
    writeUpgradeRequest(ch);
    FullHttpResponse response = responses.remove();
    assertEquals(SWITCHING_PROTOCOLS, response.status());
    response.release();
    assertNotNull(WebSocketServerProtocolHandler.getHandshaker(handshakerCtx.channel()));
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Test(org.junit.Test)

Example 75 with ChannelHandlerContext

use of io.netty.channel.ChannelHandlerContext 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)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)266 Test (org.junit.Test)150 Channel (io.netty.channel.Channel)106 ByteBuf (io.netty.buffer.ByteBuf)94 ChannelFuture (io.netty.channel.ChannelFuture)87 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)77 Bootstrap (io.netty.bootstrap.Bootstrap)69 ChannelPipeline (io.netty.channel.ChannelPipeline)68 ClosedChannelException (java.nio.channels.ClosedChannelException)63 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)57 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)56 InetSocketAddress (java.net.InetSocketAddress)54 AtomicReference (java.util.concurrent.atomic.AtomicReference)53 EventLoopGroup (io.netty.channel.EventLoopGroup)48 CountDownLatch (java.util.concurrent.CountDownLatch)47 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)45 ArrayList (java.util.ArrayList)45 List (java.util.List)43 IOException (java.io.IOException)42 Map (java.util.Map)40