Search in sources :

Example 11 with DefaultEventLoopGroup

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

the class InboundHttp2ToHttpAdapterTest method boostrapEnv.

private void boostrapEnv(int clientLatchCount, int clientLatchCount2, int serverLatchCount, int serverLatchCount2, int settingsLatchCount) throws InterruptedException {
    final CountDownLatch prefaceWrittenLatch = new CountDownLatch(1);
    clientDelegator = null;
    serverDelegator = null;
    serverConnectedChannel = null;
    maxContentLength = 1024;
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    serverLatch = new CountDownLatch(serverLatchCount);
    clientLatch = new CountDownLatch(clientLatchCount);
    serverLatch2 = new CountDownLatch(serverLatchCount2);
    clientLatch2 = new CountDownLatch(clientLatchCount2);
    settingsLatch = new CountDownLatch(settingsLatchCount);
    sb = new ServerBootstrap();
    cb = new Bootstrap();
    sb.group(new DefaultEventLoopGroup());
    sb.channel(LocalServerChannel.class);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            serverConnectedChannel = ch;
            ChannelPipeline p = ch.pipeline();
            Http2Connection connection = new DefaultHttp2Connection(true);
            serverHandler = new Http2ConnectionHandlerBuilder().frameListener(new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength).validateHttpHeaders(true).propagateSettings(true).build()).connection(connection).gracefulShutdownTimeoutMillis(0).build();
            p.addLast(serverHandler);
            serverDelegator = new HttpResponseDelegator(serverListener, serverLatch, serverLatch2);
            p.addLast(serverDelegator);
            settingsDelegator = new HttpSettingsDelegator(settingsListener, settingsLatch);
            p.addLast(settingsDelegator);
            serverChannelLatch.countDown();
        }
    });
    cb.group(new DefaultEventLoopGroup());
    cb.channel(LocalChannel.class);
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            Http2Connection connection = new DefaultHttp2Connection(false);
            clientHandler = new Http2ConnectionHandlerBuilder().frameListener(new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength).build()).connection(connection).gracefulShutdownTimeoutMillis(0).build();
            p.addLast(clientHandler);
            clientDelegator = new HttpResponseDelegator(clientListener, clientLatch, clientLatch2);
            p.addLast(clientDelegator);
            p.addLast(new ChannelHandlerAdapter() {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    Http2Exception e = getEmbeddedHttp2Exception(cause);
                    if (e != null) {
                        clientException = e;
                        clientLatch.countDown();
                    } else {
                        super.exceptionCaught(ctx, cause);
                    }
                }
            });
            p.addLast(new ChannelInboundHandlerAdapter() {

                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof Http2ConnectionPrefaceWrittenEvent) {
                        prefaceWrittenLatch.countDown();
                        ctx.pipeline().remove(this);
                    }
                }
            });
        }
    });
    serverChannel = sb.bind(new LocalAddress("InboundHttp2ToHttpAdapterTest")).sync().channel();
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    assertTrue(prefaceWrittenLatch.await(5, SECONDS));
    assertTrue(serverChannelLatch.await(5, SECONDS));
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Http2CodecUtil.getEmbeddedHttp2Exception(io.netty.handler.codec.http2.Http2CodecUtil.getEmbeddedHttp2Exception) LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Http2TestUtil.runInChannel(io.netty.handler.codec.http2.Http2TestUtil.runInChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Http2CodecUtil.getEmbeddedHttp2Exception(io.netty.handler.codec.http2.Http2CodecUtil.getEmbeddedHttp2Exception) ChannelPipeline(io.netty.channel.ChannelPipeline) ChannelHandlerAdapter(io.netty.channel.ChannelHandlerAdapter) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpObject(io.netty.handler.codec.http.HttpObject) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 12 with DefaultEventLoopGroup

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

the class LocalEcho method main.

public static void main(String[] args) throws Exception {
    // Address to bind on / connect to.
    final LocalAddress addr = new LocalAddress(PORT);
    EventLoopGroup serverGroup = new DefaultEventLoopGroup();
    // NIO event loops are also OK
    EventLoopGroup clientGroup = new NioEventLoopGroup();
    try {
        // Note that we can use any event loop to ensure certain local channels
        // are handled by the same event loop thread which drives a certain socket channel
        // to reduce the communication latency between socket channels and local channels.
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup).channel(LocalServerChannel.class).handler(new ChannelInitializer<LocalServerChannel>() {

            @Override
            public void initChannel(LocalServerChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            }
        }).childHandler(new ChannelInitializer<LocalChannel>() {

            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
            }
        });
        Bootstrap cb = new Bootstrap();
        cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {

            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
            }
        });
        // Start the server.
        sb.bind(addr).sync();
        // Start the client.
        Channel ch = cb.connect(addr).sync().channel();
        // Read commands from the stdin.
        System.out.println("Enter text (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (; ; ) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }
            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
        }
        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
    } finally {
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) LoggingHandler(io.netty.handler.logging.LoggingHandler) LocalAddress(io.netty.channel.local.LocalAddress) InputStreamReader(java.io.InputStreamReader) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) BufferedReader(java.io.BufferedReader) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 13 with DefaultEventLoopGroup

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

the class SniClientTest method testSniClient.

private static void testSniClient(SslProvider sslClientProvider, SslProvider sslServerProvider) throws Exception {
    final String sniHost = "sni.netty.io";
    LocalAddress address = new LocalAddress("test");
    EventLoopGroup group = new DefaultEventLoopGroup(1);
    Channel sc = null;
    Channel cc = null;
    try {
        SelfSignedCertificate cert = new SelfSignedCertificate();
        final SslContext sslServerContext = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(sslServerProvider).build();
        final Promise<String> promise = group.next().newPromise();
        ServerBootstrap sb = new ServerBootstrap();
        sc = sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addFirst(new SniHandler(new Mapping<String, SslContext>() {

                    @Override
                    public SslContext map(String input) {
                        promise.setSuccess(input);
                        return sslServerContext;
                    }
                }));
            }
        }).bind(address).syncUninterruptibly().channel();
        SslContext sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(sslClientProvider).build();
        Bootstrap cb = new Bootstrap();
        cc = cb.group(group).channel(LocalChannel.class).handler(new SslHandler(sslContext.newEngine(ByteBufAllocator.DEFAULT, sniHost, -1))).connect(address).syncUninterruptibly().channel();
        Assert.assertEquals(sniHost, promise.syncUninterruptibly().getNow());
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 14 with DefaultEventLoopGroup

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

the class SniHandlerTest method testReplaceHandler.

@Test(timeout = 30000)
public void testReplaceHandler() throws Exception {
    switch(provider) {
        case OPENSSL:
        case OPENSSL_REFCNT:
            final String sniHost = "sni.netty.io";
            LocalAddress address = new LocalAddress("testReplaceHandler-" + Math.random());
            EventLoopGroup group = new DefaultEventLoopGroup(1);
            Channel sc = null;
            Channel cc = null;
            SslContext sslContext = null;
            SelfSignedCertificate cert = new SelfSignedCertificate();
            try {
                final SslContext sslServerContext = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(provider).build();
                final Mapping<String, SslContext> mapping = new Mapping<String, SslContext>() {

                    @Override
                    public SslContext map(String input) {
                        return sslServerContext;
                    }
                };
                final Promise<Void> releasePromise = group.next().newPromise();
                final SniHandler handler = new SniHandler(mapping) {

                    @Override
                    protected void replaceHandler(ChannelHandlerContext ctx, String hostname, final SslContext sslContext) throws Exception {
                        boolean success = false;
                        try {
                            // The SniHandler's replaceHandler() method allows us to implement custom behavior.
                            // As an example, we want to release() the SslContext upon channelInactive() or rather
                            // when the SslHandler closes it's SslEngine. If you take a close look at SslHandler
                            // you'll see that it's doing it in the #handlerRemoved0() method.
                            SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
                            try {
                                SslHandler customSslHandler = new CustomSslHandler(sslContext, sslEngine) {

                                    @Override
                                    public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
                                        try {
                                            super.handlerRemoved0(ctx);
                                        } finally {
                                            releasePromise.trySuccess(null);
                                        }
                                    }
                                };
                                ctx.pipeline().replace(this, CustomSslHandler.class.getName(), customSslHandler);
                                success = true;
                            } finally {
                                if (!success) {
                                    ReferenceCountUtil.safeRelease(sslEngine);
                                }
                            }
                        } finally {
                            if (!success) {
                                ReferenceCountUtil.safeRelease(sslContext);
                                releasePromise.cancel(true);
                            }
                        }
                    }
                };
                ServerBootstrap sb = new ServerBootstrap();
                sc = sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addFirst(handler);
                    }
                }).bind(address).syncUninterruptibly().channel();
                sslContext = SslContextBuilder.forClient().sslProvider(provider).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
                Bootstrap cb = new Bootstrap();
                cc = cb.group(group).channel(LocalChannel.class).handler(new SslHandler(sslContext.newEngine(ByteBufAllocator.DEFAULT, sniHost, -1))).connect(address).syncUninterruptibly().channel();
                cc.writeAndFlush(Unpooled.wrappedBuffer("Hello, World!".getBytes())).syncUninterruptibly();
                // Notice how the server's SslContext refCnt is 1
                assertEquals(1, ((ReferenceCounted) sslServerContext).refCnt());
                // The client disconnects
                cc.close().syncUninterruptibly();
                if (!releasePromise.awaitUninterruptibly(10L, TimeUnit.SECONDS)) {
                    throw new IllegalStateException("It doesn't seem #replaceHandler() got called.");
                }
                // We should have successfully release() the SslContext
                assertEquals(0, ((ReferenceCounted) sslServerContext).refCnt());
            } finally {
                if (cc != null) {
                    cc.close().syncUninterruptibly();
                }
                if (sc != null) {
                    sc.close().syncUninterruptibly();
                }
                if (sslContext != null) {
                    ReferenceCountUtil.release(sslContext);
                }
                group.shutdownGracefully();
                cert.delete();
            }
        case JDK:
            return;
        default:
            throw new Error();
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SSLEngine(javax.net.ssl.SSLEngine) LocalChannel(io.netty.channel.local.LocalChannel) DomainNameMapping(io.netty.util.DomainNameMapping) Mapping(io.netty.util.Mapping) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) LocalAddress(io.netty.channel.local.LocalAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DecoderException(io.netty.handler.codec.DecoderException) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 15 with DefaultEventLoopGroup

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

the class LocalTransportThreadModelTest method testConcurrentMessageBufferAccess.

@Test(timeout = 30000)
@Ignore
public void testConcurrentMessageBufferAccess() throws Throwable {
    EventLoopGroup l = new DefaultEventLoopGroup(4, new DefaultThreadFactory("l"));
    EventExecutorGroup e1 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e1"));
    EventExecutorGroup e2 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e2"));
    EventExecutorGroup e3 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e3"));
    EventExecutorGroup e4 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e4"));
    EventExecutorGroup e5 = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("e5"));
    try {
        final MessageForwarder1 h1 = new MessageForwarder1();
        final MessageForwarder2 h2 = new MessageForwarder2();
        final MessageForwarder3 h3 = new MessageForwarder3();
        final MessageForwarder1 h4 = new MessageForwarder1();
        final MessageForwarder2 h5 = new MessageForwarder2();
        final MessageDiscarder h6 = new MessageDiscarder();
        final Channel ch = new LocalChannel();
        // inbound:  int -> byte[4] -> int -> int -> byte[4] -> int -> /dev/null
        // outbound: int -> int -> byte[4] -> int -> int -> byte[4] -> /dev/null
        ch.pipeline().addLast(h1).addLast(e1, h2).addLast(e2, h3).addLast(e3, h4).addLast(e4, h5).addLast(e5, h6);
        l.register(ch).sync().channel().connect(localAddr).sync();
        final int ROUNDS = 1024;
        final int ELEMS_PER_ROUNDS = 8192;
        final int TOTAL_CNT = ROUNDS * ELEMS_PER_ROUNDS;
        for (int i = 0; i < TOTAL_CNT; ) {
            final int start = i;
            final int end = i + ELEMS_PER_ROUNDS;
            i = end;
            ch.eventLoop().execute(new Runnable() {

                @Override
                public void run() {
                    for (int j = start; j < end; j++) {
                        ch.pipeline().fireChannelRead(Integer.valueOf(j));
                    }
                }
            });
        }
        while (h1.inCnt < TOTAL_CNT || h2.inCnt < TOTAL_CNT || h3.inCnt < TOTAL_CNT || h4.inCnt < TOTAL_CNT || h5.inCnt < TOTAL_CNT || h6.inCnt < TOTAL_CNT) {
            if (h1.exception.get() != null) {
                throw h1.exception.get();
            }
            if (h2.exception.get() != null) {
                throw h2.exception.get();
            }
            if (h3.exception.get() != null) {
                throw h3.exception.get();
            }
            if (h4.exception.get() != null) {
                throw h4.exception.get();
            }
            if (h5.exception.get() != null) {
                throw h5.exception.get();
            }
            if (h6.exception.get() != null) {
                throw h6.exception.get();
            }
            Thread.sleep(10);
        }
        for (int i = 0; i < TOTAL_CNT; ) {
            final int start = i;
            final int end = i + ELEMS_PER_ROUNDS;
            i = end;
            ch.pipeline().context(h6).executor().execute(new Runnable() {

                @Override
                public void run() {
                    for (int j = start; j < end; j++) {
                        ch.write(Integer.valueOf(j));
                    }
                    ch.flush();
                }
            });
        }
        while (h1.outCnt < TOTAL_CNT || h2.outCnt < TOTAL_CNT || h3.outCnt < TOTAL_CNT || h4.outCnt < TOTAL_CNT || h5.outCnt < TOTAL_CNT || h6.outCnt < TOTAL_CNT) {
            if (h1.exception.get() != null) {
                throw h1.exception.get();
            }
            if (h2.exception.get() != null) {
                throw h2.exception.get();
            }
            if (h3.exception.get() != null) {
                throw h3.exception.get();
            }
            if (h4.exception.get() != null) {
                throw h4.exception.get();
            }
            if (h5.exception.get() != null) {
                throw h5.exception.get();
            }
            if (h6.exception.get() != null) {
                throw h6.exception.get();
            }
            Thread.sleep(10);
        }
        ch.close().sync();
    } finally {
        l.shutdownGracefully();
        e1.shutdownGracefully();
        e2.shutdownGracefully();
        e3.shutdownGracefully();
        e4.shutdownGracefully();
        e5.shutdownGracefully();
        l.terminationFuture().sync();
        e1.terminationFuture().sync();
        e2.terminationFuture().sync();
        e3.terminationFuture().sync();
        e4.terminationFuture().sync();
        e5.terminationFuture().sync();
    }
}
Also used : DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) DefaultEventExecutorGroup(io.netty.util.concurrent.DefaultEventExecutorGroup) Channel(io.netty.channel.Channel) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)17 Channel (io.netty.channel.Channel)14 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)12 Bootstrap (io.netty.bootstrap.Bootstrap)10 EventLoopGroup (io.netty.channel.EventLoopGroup)9 LocalAddress (io.netty.channel.local.LocalAddress)9 LocalChannel (io.netty.channel.local.LocalChannel)9 LocalServerChannel (io.netty.channel.local.LocalServerChannel)9 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)8 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)7 Test (org.junit.Test)7 ChannelFuture (io.netty.channel.ChannelFuture)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 ChannelHandler (io.netty.channel.ChannelHandler)3 ChannelPipeline (io.netty.channel.ChannelPipeline)3 DefaultEventExecutorGroup (io.netty.util.concurrent.DefaultEventExecutorGroup)3 DefaultThreadFactory (io.netty.util.concurrent.DefaultThreadFactory)3 EventExecutorGroup (io.netty.util.concurrent.EventExecutorGroup)3 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)2 LocalEventLoopGroup (io.netty.channel.local.LocalEventLoopGroup)2