Search in sources :

Example 61 with NettyContext

use of reactor.ipc.netty.NettyContext in project reactor-netty by reactor.

the class UdpClientTest method smokeTest.

@Test
public void smokeTest() throws Exception {
    LoopResources resources = LoopResources.create("test");
    CountDownLatch latch = new CountDownLatch(4);
    NettyContext server = UdpServer.create(ops -> ops.port(0).loopResources(resources)).newHandler((in, out) -> in.receiveObject().map(o -> {
        if (o instanceof DatagramPacket) {
            DatagramPacket received = (DatagramPacket) o;
            System.out.println("Server received " + received.content().toString(CharsetUtil.UTF_8));
            ByteBuf buf1 = Unpooled.copiedBuffer("echo ", CharsetUtil.UTF_8);
            ByteBuf buf2 = Unpooled.copiedBuffer(buf1, received.content().retain());
            return new DatagramPacket(buf2, received.sender());
        } else {
            return Mono.error(new Exception());
        }
    }).flatMap(p -> out.sendObject(p))).block(Duration.ofSeconds(30));
    NettyContext client1 = UdpClient.create(ops -> ops.port(server.address().getPort()).loopResources(resources)).newHandler((in, out) -> {
        in.receive().subscribe(b -> {
            System.out.println("Client1 received " + b.toString(CharsetUtil.UTF_8));
            latch.countDown();
        });
        return out.sendString(Mono.just("ping1")).then(out.sendString(Mono.just("ping2"))).neverComplete();
    }).block(Duration.ofSeconds(30));
    NettyContext client2 = UdpClient.create(ops -> ops.port(server.address().getPort()).loopResources(resources)).newHandler((in, out) -> {
        in.receive().subscribe(b -> {
            System.out.println("Client2 received " + b.toString(CharsetUtil.UTF_8));
            latch.countDown();
        });
        return out.sendString(Mono.just("ping3")).then(out.sendString(Mono.just("ping4"))).neverComplete();
    }).block(Duration.ofSeconds(30));
    assertTrue(latch.await(30, TimeUnit.SECONDS));
    server.dispose();
    client1.dispose();
    client2.dispose();
}
Also used : Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) Unpooled(io.netty.buffer.Unpooled) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) Duration(java.time.Duration) DatagramPacket(io.netty.channel.socket.DatagramPacket) CharsetUtil(io.netty.util.CharsetUtil) NettyContext(reactor.ipc.netty.NettyContext) LoopResources(reactor.ipc.netty.resources.LoopResources) LoopResources(reactor.ipc.netty.resources.LoopResources) DatagramPacket(io.netty.channel.socket.DatagramPacket) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) NettyContext(reactor.ipc.netty.NettyContext) Test(org.junit.Test)

Example 62 with NettyContext

use of reactor.ipc.netty.NettyContext in project reactor-netty by reactor.

the class UdpServerTests method supportsUdpMulticast.

@Test
public void supportsUdpMulticast() throws Exception {
    final int port = SocketUtils.findAvailableUdpPort();
    final CountDownLatch latch = new CountDownLatch(Schedulers.DEFAULT_POOL_SIZE);
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    final InetAddress multicastGroup = InetAddress.getByName("230.0.0.1");
    final NetworkInterface multicastInterface = findMulticastEnabledIPv4Interface();
    log.info("Using network interface '{}' for multicast", multicastInterface);
    final Collection<NettyContext> servers = new ArrayList<>();
    LoopResources resources = LoopResources.create("test");
    for (int i = 0; i < 4; i++) {
        NettyContext server = UdpServer.create(opts -> opts.option(ChannelOption.SO_REUSEADDR, true).connectAddress(() -> new InetSocketAddress(port)).protocolFamily(InternetProtocolFamily.IPv4).loopResources(resources)).newHandler((in, out) -> {
            Flux.<NetworkInterface>generate(s -> {
                if (ifaces.hasMoreElements()) {
                    s.next(ifaces.nextElement());
                } else {
                    s.complete();
                }
            }).flatMap(iface -> {
                if (isMulticastEnabledIPv4Interface(iface)) {
                    return in.join(multicastGroup, iface);
                }
                return Flux.empty();
            }).thenMany(in.receive().asByteArray()).log().subscribe(bytes -> {
                if (bytes.length == 1024) {
                    latch.countDown();
                }
            });
            return Flux.never();
        }).block(Duration.ofSeconds(30));
        servers.add(server);
    }
    for (int i = 0; i < Schedulers.DEFAULT_POOL_SIZE; i++) {
        threadPool.submit(() -> {
            try {
                MulticastSocket multicast = new MulticastSocket();
                multicast.joinGroup(new InetSocketAddress(multicastGroup, port), multicastInterface);
                byte[] data = new byte[1024];
                new Random().nextBytes(data);
                multicast.send(new DatagramPacket(data, data.length, multicastGroup, port));
                multicast.close();
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }).get(5, TimeUnit.SECONDS);
    }
    latch.await(5, TimeUnit.SECONDS);
    assertThat("latch was not counted down enough: " + latch.getCount() + " left on " + (4 ^ 2), latch.getCount() == 0);
    for (NettyContext s : servers) {
        s.dispose();
    }
}
Also used : ChannelOption(io.netty.channel.ChannelOption) Enumeration(java.util.Enumeration) DatagramChannel(java.nio.channels.DatagramChannel) Random(java.util.Random) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) SocketException(java.net.SocketException) Loggers(reactor.util.Loggers) Duration(java.time.Duration) After(org.junit.After) Logger(reactor.util.Logger) InternetProtocolFamily(io.netty.channel.socket.InternetProtocolFamily) Schedulers(reactor.core.scheduler.Schedulers) SocketUtils(reactor.ipc.netty.SocketUtils) LoopResources(reactor.ipc.netty.resources.LoopResources) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) Collection(java.util.Collection) NetworkInterface(java.net.NetworkInterface) NetUtil(io.netty.util.NetUtil) IOException(java.io.IOException) Test(org.junit.Test) Inet4Address(java.net.Inet4Address) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) Ignore(org.junit.Ignore) MulticastSocket(java.net.MulticastSocket) NettyContext(reactor.ipc.netty.NettyContext) DatagramPacket(java.net.DatagramPacket) MulticastSocket(java.net.MulticastSocket) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) NetworkInterface(java.net.NetworkInterface) CountDownLatch(java.util.concurrent.CountDownLatch) SocketException(java.net.SocketException) IOException(java.io.IOException) NettyContext(reactor.ipc.netty.NettyContext) Random(java.util.Random) LoopResources(reactor.ipc.netty.resources.LoopResources) DatagramPacket(java.net.DatagramPacket) InetAddress(java.net.InetAddress) Test(org.junit.Test)

Example 63 with NettyContext

use of reactor.ipc.netty.NettyContext in project reactor-netty by reactor.

the class HttpClientTest method prematureCancel.

@Test
public void prematureCancel() throws Exception {
    DirectProcessor<Void> signal = DirectProcessor.create();
    NettyContext x = TcpServer.create("localhost", 0).newHandler((in, out) -> {
        signal.onComplete();
        return out.context(c -> c.addHandlerFirst(new HttpResponseEncoder())).sendObject(Mono.delay(Duration.ofSeconds(2)).map(t -> new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.PROCESSING))).neverComplete();
    }).block(Duration.ofSeconds(30));
    StepVerifier.create(createHttpClientForContext(x).get("/").timeout(signal)).verifyError(TimeoutException.class);
// Thread.sleep(1000000);
}
Also used : HttpResources(reactor.ipc.netty.http.HttpResources) HttpVersion(io.netty.handler.codec.http.HttpVersion) StepVerifier(reactor.test.StepVerifier) URISyntaxException(java.net.URISyntaxException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TimeoutException(java.util.concurrent.TimeoutException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Unpooled(io.netty.buffer.Unpooled) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) Duration(java.time.Duration) CharsetUtil(io.netty.util.CharsetUtil) Path(java.nio.file.Path) HttpServer(reactor.ipc.netty.http.server.HttpServer) DirectProcessor(reactor.core.publisher.DirectProcessor) SslContext(io.netty.handler.ssl.SslContext) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) FutureMono(reactor.ipc.netty.FutureMono) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) PoolResources(reactor.ipc.netty.resources.PoolResources) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) SSLException(javax.net.ssl.SSLException) Ignore(org.junit.Ignore) Paths(java.nio.file.Paths) TcpServer(reactor.ipc.netty.tcp.TcpServer) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) NettyContext(reactor.ipc.netty.NettyContext) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AbortedException(reactor.ipc.netty.channel.AbortedException) Assert(org.junit.Assert) InputStream(java.io.InputStream) Proxy(reactor.ipc.netty.options.ClientProxyOptions.Proxy) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) NettyContext(reactor.ipc.netty.NettyContext) Test(org.junit.Test)

Example 64 with NettyContext

use of reactor.ipc.netty.NettyContext in project reactor-netty by reactor.

the class HttpClientTest method testUserAgent.

@Test
public void testUserAgent() {
    NettyContext c = HttpServer.create(0).newHandler((req, resp) -> {
        Assert.assertTrue("" + req.requestHeaders().get(HttpHeaderNames.USER_AGENT), req.requestHeaders().contains(HttpHeaderNames.USER_AGENT) && req.requestHeaders().get(HttpHeaderNames.USER_AGENT).equals(HttpClient.USER_AGENT));
        return resp;
    }).block();
    HttpClientResponse resp = HttpClient.create(c.address().getPort()).get("/").block();
    resp.dispose();
    c.dispose();
}
Also used : HttpResources(reactor.ipc.netty.http.HttpResources) HttpVersion(io.netty.handler.codec.http.HttpVersion) StepVerifier(reactor.test.StepVerifier) URISyntaxException(java.net.URISyntaxException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TimeoutException(java.util.concurrent.TimeoutException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Unpooled(io.netty.buffer.Unpooled) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) Duration(java.time.Duration) CharsetUtil(io.netty.util.CharsetUtil) Path(java.nio.file.Path) HttpServer(reactor.ipc.netty.http.server.HttpServer) DirectProcessor(reactor.core.publisher.DirectProcessor) SslContext(io.netty.handler.ssl.SslContext) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) FutureMono(reactor.ipc.netty.FutureMono) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) PoolResources(reactor.ipc.netty.resources.PoolResources) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) SSLException(javax.net.ssl.SSLException) Ignore(org.junit.Ignore) Paths(java.nio.file.Paths) TcpServer(reactor.ipc.netty.tcp.TcpServer) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) NettyContext(reactor.ipc.netty.NettyContext) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AbortedException(reactor.ipc.netty.channel.AbortedException) Assert(org.junit.Assert) InputStream(java.io.InputStream) Proxy(reactor.ipc.netty.options.ClientProxyOptions.Proxy) NettyContext(reactor.ipc.netty.NettyContext) Test(org.junit.Test)

Example 65 with NettyContext

use of reactor.ipc.netty.NettyContext in project reactor-netty by reactor.

the class HttpClientTest method doTestGzip.

private void doTestGzip(boolean gzipEnabled) {
    String expectedResponse = gzipEnabled ? "gzip" : "no gzip";
    NettyContext server = HttpServer.create(0).newHandler((req, res) -> res.sendString(Mono.just(req.requestHeaders().get(HttpHeaderNames.ACCEPT_ENCODING, "no gzip")))).block(Duration.ofSeconds(30));
    StepVerifier.create(HttpClient.create(ops -> ops.port(server.address().getPort()).compression(gzipEnabled)).get("/").flatMap(r -> r.receive().asString().elementAt(0).zipWith(Mono.just(r)))).expectNextMatches(tuple -> {
        tuple.getT2().dispose();
        return expectedResponse.equals(tuple.getT1());
    }).expectComplete().verify(Duration.ofSeconds(30));
    server.dispose();
}
Also used : HttpResources(reactor.ipc.netty.http.HttpResources) HttpVersion(io.netty.handler.codec.http.HttpVersion) StepVerifier(reactor.test.StepVerifier) URISyntaxException(java.net.URISyntaxException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TimeoutException(java.util.concurrent.TimeoutException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Unpooled(io.netty.buffer.Unpooled) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) Duration(java.time.Duration) CharsetUtil(io.netty.util.CharsetUtil) Path(java.nio.file.Path) HttpServer(reactor.ipc.netty.http.server.HttpServer) DirectProcessor(reactor.core.publisher.DirectProcessor) SslContext(io.netty.handler.ssl.SslContext) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) FutureMono(reactor.ipc.netty.FutureMono) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) PoolResources(reactor.ipc.netty.resources.PoolResources) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) SSLException(javax.net.ssl.SSLException) Ignore(org.junit.Ignore) Paths(java.nio.file.Paths) TcpServer(reactor.ipc.netty.tcp.TcpServer) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) NettyContext(reactor.ipc.netty.NettyContext) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AbortedException(reactor.ipc.netty.channel.AbortedException) Assert(org.junit.Assert) InputStream(java.io.InputStream) Proxy(reactor.ipc.netty.options.ClientProxyOptions.Proxy) NettyContext(reactor.ipc.netty.NettyContext)

Aggregations

NettyContext (reactor.ipc.netty.NettyContext)92 Test (org.junit.Test)87 Mono (reactor.core.publisher.Mono)86 Duration (java.time.Duration)83 Flux (reactor.core.publisher.Flux)78 InetSocketAddress (java.net.InetSocketAddress)65 HttpServer (reactor.ipc.netty.http.server.HttpServer)63 HttpClient (reactor.ipc.netty.http.client.HttpClient)61 CountDownLatch (java.util.concurrent.CountDownLatch)60 StepVerifier (reactor.test.StepVerifier)60 AtomicReference (java.util.concurrent.atomic.AtomicReference)56 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)53 Unpooled (io.netty.buffer.Unpooled)50 TimeUnit (java.util.concurrent.TimeUnit)44 StandardCharsets (java.nio.charset.StandardCharsets)43 Ignore (org.junit.Ignore)43 SslContext (io.netty.handler.ssl.SslContext)42 SslContextBuilder (io.netty.handler.ssl.SslContextBuilder)42 InsecureTrustManagerFactory (io.netty.handler.ssl.util.InsecureTrustManagerFactory)42 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)42