Search in sources :

Example 56 with LocalAddress

use of io.netty.channel.local.LocalAddress in project grpc-java by grpc.

the class Http2NettyLocalChannelTest method createChannel.

@Override
protected ManagedChannel createChannel() {
    NettyChannelBuilder builder = NettyChannelBuilder.forAddress(new LocalAddress("in-process-1")).negotiationType(NegotiationType.PLAINTEXT).channelType(LocalChannel.class).flowControlWindow(65 * 1024).maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
    io.grpc.internal.TestingAccessor.setStatsContextFactory(builder, getClientStatsFactory());
    return builder.build();
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder)

Example 57 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)

Example 58 with LocalAddress

use of io.netty.channel.local.LocalAddress in project activemq-artemis by apache.

the class NettyAcceptor method startServerChannels.

private void startServerChannels() {
    String[] hosts = TransportConfiguration.splitHosts(host);
    for (String h : hosts) {
        SocketAddress address;
        if (useInvm) {
            address = new LocalAddress(h);
        } else {
            address = new InetSocketAddress(h, port);
        }
        Channel serverChannel = bootstrap.bind(address).syncUninterruptibly().channel();
        serverChannelGroup.add(serverChannel);
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) InetSocketAddress(java.net.InetSocketAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) KQueueServerSocketChannel(io.netty.channel.kqueue.KQueueServerSocketChannel) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) Channel(io.netty.channel.Channel) SimpleString(org.apache.activemq.artemis.api.core.SimpleString) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 59 with LocalAddress

use of io.netty.channel.local.LocalAddress in project jocean-http by isdom.

the class DefaultHttpClientTestCase method testInitiatorInteractionSuccessAsHttps.

@Test(timeout = 5000)
public void testInitiatorInteractionSuccessAsHttps() throws Exception {
    // 配置 池化分配器 为 取消缓存,使用 Heap
    configDefaultAllocator();
    final PooledByteBufAllocator allocator = defaultAllocator();
    assertEquals(0, allActiveAllocationsCount(allocator));
    final BlockingQueue<HttpTrade> trades = new ArrayBlockingQueue<>(1);
    final String addr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(addr, trades, enableSSL4ServerWithSelfSigned(), Feature.ENABLE_LOGGING_OVER_SSL);
    final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), enableSSL4Client(), Feature.ENABLE_LOGGING_OVER_SSL);
    try {
        startInteraction(client.initiator().remoteAddress(new LocalAddress(addr)), Observable.just(fullHttpRequest()), new Interaction() {

            @Override
            public void interact(final HttpInitiator initiator, final Observable<DisposableWrapper<FullHttpResponse>> getresp) throws Exception {
                final Observable<DisposableWrapper<FullHttpResponse>> cached = getresp.cache();
                // initiator 开始发送 请求
                cached.subscribe();
                LOG.debug("before get tarde");
                // server side recv req
                final HttpTrade trade = trades.take();
                LOG.debug("after get tarde");
                // recv all request
                trade.inbound().toCompletable().await();
                final ByteBuf svrRespContent = allocator.buffer(CONTENT.length).writeBytes(CONTENT);
                // send back resp
                trade.outbound(TestHttpUtil.buildByteBufResponse("text/plain", svrRespContent));
                // wait for recv all resp at client side
                cached.toCompletable().await();
                svrRespContent.release();
                assertTrue(Arrays.equals(dumpResponseContentAsBytes(cached), CONTENT));
            }
        });
    } finally {
        assertEquals(0, allActiveAllocationsCount(allocator));
        client.close();
        server.unsubscribe();
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) DisposableWrapper(org.jocean.idiom.DisposableWrapper) ByteBuf(io.netty.buffer.ByteBuf) SSLException(javax.net.ssl.SSLException) TransportException(org.jocean.http.TransportException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ConnectableObservable(rx.observables.ConnectableObservable) Observable(rx.Observable) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) HttpInitiator(org.jocean.http.client.HttpClient.HttpInitiator) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Subscription(rx.Subscription) Test(org.junit.Test)

Example 60 with LocalAddress

use of io.netty.channel.local.LocalAddress in project jocean-http by isdom.

the class DefaultHttpClientTestCase method testInitiatorInteractionFailedAsHttp10ConnectionCloseMissingPartContent.

@Test(timeout = 5000)
public void testInitiatorInteractionFailedAsHttp10ConnectionCloseMissingPartContent() throws Exception {
    // 配置 池化分配器 为 取消缓存,使用 Heap
    configDefaultAllocator();
    final PooledByteBufAllocator allocator = defaultAllocator();
    final BlockingQueue<HttpTrade> trades = new ArrayBlockingQueue<>(1);
    final String addr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(addr, trades, Feature.ENABLE_LOGGING);
    final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING);
    try {
        final HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/");
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        startInteraction(client.initiator().remoteAddress(new LocalAddress(addr)), Observable.just(request), new Interaction() {

            @Override
            public void interact(final HttpInitiator initiator, final Observable<DisposableWrapper<FullHttpResponse>> getresp) throws Exception {
                final CountDownLatch cdl4initiator = new CountDownLatch(1);
                initiator.doOnTerminate(new Action0() {

                    @Override
                    public void call() {
                        cdl4initiator.countDown();
                    }
                });
                assertEquals(0, allActiveAllocationsCount(allocator));
                final TestSubscriber<DisposableWrapper<FullHttpResponse>> subscriber = new TestSubscriber<>();
                getresp.subscribe(subscriber);
                // server side recv req
                final HttpTrade trade = trades.take();
                // recv all request
                trade.inbound().toCompletable().await();
                final ByteBuf svrRespContent = allocator.buffer(CONTENT.length).writeBytes(CONTENT);
                // for HTTP 1.0 Connection: Close response behavior
                final FullHttpResponse fullrespfromsvr = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK, svrRespContent);
                fullrespfromsvr.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                // missing Content-Length
                fullrespfromsvr.headers().set(HttpHeaderNames.CONTENT_LENGTH, fullrespfromsvr.content().readableBytes() + 1);
                fullrespfromsvr.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
                trade.outbound(Observable.just(fullrespfromsvr));
                TerminateAware.Util.awaitTerminated(trade);
                subscriber.awaitTerminalEvent();
                assertTrue(svrRespContent.release());
                subscriber.assertError(TransportException.class);
                // assertTrue(subscriber.getValueCount() > 0);
                cdl4initiator.await();
                assertEquals(0, allActiveAllocationsCount(allocator));
            }
        });
    } finally {
        client.close();
        server.unsubscribe();
    }
}
Also used : DisposableWrapper(org.jocean.idiom.DisposableWrapper) ByteBuf(io.netty.buffer.ByteBuf) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) HttpInitiator(org.jocean.http.client.HttpClient.HttpInitiator) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Subscription(rx.Subscription) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Action0(rx.functions.Action0) LocalAddress(io.netty.channel.local.LocalAddress) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) CountDownLatch(java.util.concurrent.CountDownLatch) TransportException(org.jocean.http.TransportException) SSLException(javax.net.ssl.SSLException) TransportException(org.jocean.http.TransportException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TestSubscriber(rx.observers.TestSubscriber) Test(org.junit.Test)

Aggregations

LocalAddress (io.netty.channel.local.LocalAddress)116 Bootstrap (io.netty.bootstrap.Bootstrap)66 LocalChannel (io.netty.channel.local.LocalChannel)66 LocalServerChannel (io.netty.channel.local.LocalServerChannel)66 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)63 Channel (io.netty.channel.Channel)61 Test (org.junit.Test)47 Test (org.junit.jupiter.api.Test)39 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)32 EventLoopGroup (io.netty.channel.EventLoopGroup)32 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)31 PooledByteBufAllocator (io.netty.buffer.PooledByteBufAllocator)28 ConnectException (java.net.ConnectException)27 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)27 Subscription (rx.Subscription)27 HttpInitiator (org.jocean.http.client.HttpClient.HttpInitiator)26 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)26 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)25 ChannelFuture (io.netty.channel.ChannelFuture)24 SSLException (javax.net.ssl.SSLException)22