Search in sources :

Example 96 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class ResolveAddressHandlerTest method testResolve.

private static void testResolve(boolean fail) {
    AddressResolverGroup<SocketAddress> resolverGroup = new TestResolverGroup(fail);
    Bootstrap cb = new Bootstrap();
    cb.group(group).channel(LocalChannel.class).handler(new ResolveAddressHandler(resolverGroup));
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            ctx.close();
        }
    });
    // Start server
    Channel sc = sb.bind(RESOLVED).syncUninterruptibly().channel();
    ChannelFuture future = cb.connect(UNRESOLVED).awaitUninterruptibly();
    try {
        if (fail) {
            assertSame(ERROR, future.cause());
        } else {
            assertTrue(future.isSuccess());
        }
        future.channel().close().syncUninterruptibly();
    } finally {
        future.channel().close().syncUninterruptibly();
        sc.close().syncUninterruptibly();
        resolverGroup.close();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SocketAddress(java.net.SocketAddress) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 97 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class PcapWriteHandlerTest method tcpV4.

@Test
public void tcpV4() throws InterruptedException, ExecutionException {
    final ByteBuf byteBuf = Unpooled.buffer();
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup clientGroup = new NioEventLoopGroup();
    // Configure the echo server
    ServerBootstrap sb = new ServerBootstrap();
    final Promise<Boolean> dataReadPromise = bossGroup.next().newPromise();
    sb.group(bossGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new PcapWriteHandler(new ByteBufOutputStream(byteBuf)));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    ctx.write(msg);
                }

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) {
                    ctx.flush();
                    dataReadPromise.setSuccess(true);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                    ctx.close();
                }
            });
        }
    });
    // Start the server.
    ChannelFuture serverChannelFuture = sb.bind(new InetSocketAddress("127.0.0.1", 0)).sync();
    assertTrue(serverChannelFuture.isSuccess());
    // configure the client
    Bootstrap cb = new Bootstrap();
    final Promise<Boolean> dataWrittenPromise = clientGroup.next().newPromise();
    cb.group(clientGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelActive(ChannelHandlerContext ctx) {
                    ctx.writeAndFlush(Unpooled.wrappedBuffer("Meow".getBytes()));
                    dataWrittenPromise.setSuccess(true);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                    ctx.close();
                }
            });
        }
    });
    // Start the client.
    ChannelFuture clientChannelFuture = cb.connect(serverChannelFuture.channel().localAddress()).sync();
    assertTrue(clientChannelFuture.isSuccess());
    assertTrue(dataWrittenPromise.await(5, TimeUnit.SECONDS));
    assertTrue(dataReadPromise.await(5, TimeUnit.SECONDS));
    clientChannelFuture.channel().close().sync();
    serverChannelFuture.channel().close().sync();
    // Shut down all event loops to terminate all threads.
    assertTrue(clientGroup.shutdownGracefully().sync().isSuccess());
    assertTrue(bossGroup.shutdownGracefully().sync().isSuccess());
    verifyGlobalHeaders(byteBuf);
    // Verify Pcap Packet Header
    // Just read, we don't care about timestamps for now
    byteBuf.readInt();
    // Just read, we don't care about timestamps for now
    byteBuf.readInt();
    // Length of Packet Saved In Pcap
    assertEquals(54, byteBuf.readInt());
    // Actual Length of Packet
    assertEquals(54, byteBuf.readInt());
    // -------------------------------------------- Verify Packet --------------------------------------------
    // Verify Ethernet Packet
    ByteBuf ethernetPacket = byteBuf.readSlice(54);
    ByteBuf dstMac = ethernetPacket.readSlice(6);
    ByteBuf srcMac = ethernetPacket.readSlice(6);
    assertArrayEquals(new byte[] { 0, 0, 94, 0, 83, -1 }, ByteBufUtil.getBytes(dstMac));
    assertArrayEquals(new byte[] { 0, 0, 94, 0, 83, 0 }, ByteBufUtil.getBytes(srcMac));
    assertEquals(0x0800, ethernetPacket.readShort());
    // Verify IPv4 Packet
    ByteBuf ipv4Packet = ethernetPacket.readSlice(32);
    // Version + IHL
    assertEquals(0x45, ipv4Packet.readByte());
    // DSCP
    assertEquals(0x00, ipv4Packet.readByte());
    // Length
    assertEquals(40, ipv4Packet.readShort());
    // Identification
    assertEquals(0x0000, ipv4Packet.readShort());
    // Fragment
    assertEquals(0x0000, ipv4Packet.readShort());
    // TTL
    assertEquals((byte) 0xff, ipv4Packet.readByte());
    // Protocol
    assertEquals((byte) 6, ipv4Packet.readByte());
    // Checksum
    assertEquals(0, ipv4Packet.readShort());
    InetSocketAddress serverAddr = (InetSocketAddress) serverChannelFuture.channel().localAddress();
    // Source IPv4 Address
    assertEquals(NetUtil.ipv4AddressToInt((Inet4Address) serverAddr.getAddress()), ipv4Packet.readInt());
    // Destination IPv4 Address
    ipv4Packet.readInt();
    InetSocketAddress clientAddr = (InetSocketAddress) clientChannelFuture.channel().localAddress();
    // Verify ports
    ByteBuf tcpPacket = ipv4Packet.readSlice(12);
    // Source Port
    assertEquals(clientAddr.getPort() & 0xffff, tcpPacket.readUnsignedShort());
    // Destination Port
    assertEquals(serverAddr.getPort() & 0xffff, tcpPacket.readUnsignedShort());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Inet4Address(java.net.Inet4Address) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 98 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class ApplicationProtocolNegotiationHandlerTest method testBufferMessagesUntilHandshakeComplete.

private void testBufferMessagesUntilHandshakeComplete(final Consumer<ChannelHandlerContext> pipelineConfigurator) throws Exception {
    final AtomicReference<byte[]> channelReadData = new AtomicReference<byte[]>();
    final AtomicBoolean channelReadCompleteCalled = new AtomicBoolean(false);
    ChannelHandler alpnHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {

        @Override
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
            assertEquals(ApplicationProtocolNames.HTTP_1_1, protocol);
            ctx.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    channelReadData.set((byte[]) msg);
                }

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) {
                    channelReadCompleteCalled.set(true);
                }
            });
            if (pipelineConfigurator != null) {
                pipelineConfigurator.consume(ctx);
            }
        }
    };
    SSLEngine engine = SSLContext.getDefault().createSSLEngine();
    // This test is mocked/simulated and doesn't go through full TLS handshake. Currently only JDK SSLEngineImpl
    // client mode will generate a close_notify.
    engine.setUseClientMode(true);
    final byte[] someBytes = new byte[1024];
    EmbeddedChannel channel = new EmbeddedChannel(new SslHandler(engine), new ChannelInboundHandlerAdapter() {

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
            if (evt == SslHandshakeCompletionEvent.SUCCESS) {
                ctx.fireChannelRead(someBytes);
            }
            ctx.fireUserEventTriggered(evt);
        }
    }, alpnHandler);
    channel.pipeline().fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);
    assertNull(channel.pipeline().context(alpnHandler));
    assertArrayEquals(someBytes, channelReadData.get());
    assertTrue(channelReadCompleteCalled.get());
    assertNull(channel.readInbound());
    assertTrue(channel.finishAndReleaseAll());
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 99 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class LocalTransportThreadModelTest method init.

@BeforeAll
public static void init() {
    // Configure a test server
    group = new DefaultEventLoopGroup();
    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() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    // Discard
                    ReferenceCountUtil.release(msg);
                }
            });
        }
    });
    localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress();
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) BeforeAll(org.junit.jupiter.api.BeforeAll)

Example 100 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class FixedChannelPoolTest method testAcquireNewConnection.

@Test
public void testAcquireNewConnection() throws Exception {
    LocalAddress addr = new LocalAddress(getLocalAddrId());
    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 TestChannelPoolHandler();
    ChannelPool pool = new FixedChannelPool(cb, handler, ChannelHealthChecker.ACTIVE, AcquireTimeoutAction.NEW, 500, 1, Integer.MAX_VALUE);
    Channel channel = pool.acquire().syncUninterruptibly().getNow();
    Channel channel2 = pool.acquire().syncUninterruptibly().getNow();
    assertNotSame(channel, channel2);
    sc.close().syncUninterruptibly();
    channel.close().syncUninterruptibly();
    channel2.close().syncUninterruptibly();
    pool.close();
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Aggregations

ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)248 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)192 Channel (io.netty.channel.Channel)132 Bootstrap (io.netty.bootstrap.Bootstrap)109 Test (org.junit.jupiter.api.Test)102 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)99 ChannelFuture (io.netty.channel.ChannelFuture)71 CountDownLatch (java.util.concurrent.CountDownLatch)70 InetSocketAddress (java.net.InetSocketAddress)66 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)54 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)53 EventLoopGroup (io.netty.channel.EventLoopGroup)52 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)51 ByteBuf (io.netty.buffer.ByteBuf)47 AtomicReference (java.util.concurrent.atomic.AtomicReference)47 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)46 ClosedChannelException (java.nio.channels.ClosedChannelException)46 LocalServerChannel (io.netty.channel.local.LocalServerChannel)44 LocalChannel (io.netty.channel.local.LocalChannel)42 SocketChannel (io.netty.channel.socket.SocketChannel)39