Search in sources :

Example 26 with LocalAddress

use of io.netty.channel.local.LocalAddress in project netty by netty.

the class Http2ConnectionRoundtripTest method bootstrapEnv.

private void bootstrapEnv(int dataCountDown, int settingsAckCount, int requestCountDown, int trailersCountDown, int goAwayCountDown) throws Exception {
    final CountDownLatch prefaceWrittenLatch = new CountDownLatch(1);
    requestLatch = new CountDownLatch(requestCountDown);
    serverSettingsAckLatch = new CountDownLatch(settingsAckCount);
    dataLatch = new CountDownLatch(dataCountDown);
    trailersLatch = new CountDownLatch(trailersCountDown);
    goAwayLatch = goAwayCountDown > 0 ? new CountDownLatch(goAwayCountDown) : requestLatch;
    sb = new ServerBootstrap();
    cb = new Bootstrap();
    final AtomicReference<Http2ConnectionHandler> serverHandlerRef = new AtomicReference<Http2ConnectionHandler>();
    final CountDownLatch serverInitLatch = new CountDownLatch(1);
    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();
            serverFrameCountDown = new FrameCountDown(serverListener, serverSettingsAckLatch, requestLatch, dataLatch, trailersLatch, goAwayLatch);
            serverHandlerRef.set(new Http2ConnectionHandlerBuilder().server(true).frameListener(serverFrameCountDown).validateHeaders(false).build());
            p.addLast(serverHandlerRef.get());
            serverInitLatch.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();
            p.addLast(new Http2ConnectionHandlerBuilder().server(false).frameListener(clientListener).validateHeaders(false).gracefulShutdownTimeoutMillis(0).build());
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof Http2ConnectionPrefaceWrittenEvent) {
                        prefaceWrittenLatch.countDown();
                        ctx.pipeline().remove(this);
                    }
                }
            });
        }
    });
    serverChannel = sb.bind(new LocalAddress("Http2ConnectionRoundtripTest")).sync().channel();
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    assertTrue(prefaceWrittenLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    http2Client = clientChannel.pipeline().get(Http2ConnectionHandler.class);
    assertTrue(serverInitLatch.await(DEFAULT_AWAIT_TIMEOUT_SECONDS, SECONDS));
    http2Server = serverHandlerRef.get();
}
Also used : FrameCountDown(io.netty.handler.codec.http2.Http2TestUtil.FrameCountDown) ChannelFuture(io.netty.channel.ChannelFuture) 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) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 27 with LocalAddress

use of io.netty.channel.local.LocalAddress 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 28 with LocalAddress

use of io.netty.channel.local.LocalAddress 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 29 with LocalAddress

use of io.netty.channel.local.LocalAddress 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 30 with LocalAddress

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

Aggregations

LocalAddress (io.netty.channel.local.LocalAddress)34 Bootstrap (io.netty.bootstrap.Bootstrap)26 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)25 LocalChannel (io.netty.channel.local.LocalChannel)24 Test (org.junit.Test)24 LocalServerChannel (io.netty.channel.local.LocalServerChannel)23 Channel (io.netty.channel.Channel)22 EventLoopGroup (io.netty.channel.EventLoopGroup)18 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)16 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)15 LocalEventLoopGroup (io.netty.channel.local.LocalEventLoopGroup)14 ChannelFuture (io.netty.channel.ChannelFuture)7 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 TimeoutException (java.util.concurrent.TimeoutException)6 ClosedChannelException (java.nio.channels.ClosedChannelException)4 ChannelPipeline (io.netty.channel.ChannelPipeline)3 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)3 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)3 InetSocketAddress (java.net.InetSocketAddress)3