Search in sources :

Example 36 with Connection

use of reactor.netty.Connection in project reactor-netty by reactor.

the class UdpClientTest method testIssue192.

@Test
void testIssue192() throws Exception {
    LoopResources resources = LoopResources.create("testIssue192");
    NioEventLoopGroup loop = new NioEventLoopGroup(1);
    UdpServer server = UdpServer.create().runOn(resources);
    UdpClient client = UdpClient.create().resolver(spec -> spec.runOn(loop)).runOn(resources);
    assertThat(Thread.getAllStackTraces().keySet().stream().noneMatch(t -> t.getName().startsWith("testIssue192"))).isTrue();
    Connection conn1 = null;
    Connection conn2 = null;
    try {
        conn1 = server.bindNow();
        conn2 = client.connectNow();
        assertThat(conn1).isNotNull();
        assertThat(conn2).isNotNull();
        assertThat(Thread.getAllStackTraces().keySet().stream().anyMatch(t -> t.getName().startsWith("testIssue192"))).isTrue();
    } finally {
        if (conn1 != null) {
            conn1.disposeNow();
        }
        if (conn2 != null) {
            conn2.disposeNow();
        }
        resources.disposeLater().block(Duration.ofSeconds(5));
        loop.shutdownGracefully().get(5, TimeUnit.SECONDS);
    }
}
Also used : LoopResources(reactor.netty.resources.LoopResources) StepVerifier(reactor.test.StepVerifier) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) Files(java.nio.file.Files) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) DomainDatagramPacket(io.netty.channel.unix.DomainDatagramPacket) Mono(reactor.core.publisher.Mono) InetSocketAddress(java.net.InetSocketAddress) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Unpooled(io.netty.buffer.Unpooled) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) Duration(java.time.Duration) DatagramPacket(io.netty.channel.socket.DatagramPacket) CharsetUtil(io.netty.util.CharsetUtil) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Connection(reactor.netty.Connection) LoopResources(reactor.netty.resources.LoopResources) Connection(reactor.netty.Connection) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.jupiter.api.Test)

Example 37 with Connection

use of reactor.netty.Connection in project reactor-netty by reactor.

the class TcpServerTests method assertSendFile.

private void assertSendFile(Function<NettyOutbound, NettyOutbound> fn) throws Exception {
    DisposableServer context = TcpServer.create().handle((in, out) -> in.receive().asString().flatMap(word -> "GOGOGO".equals(word) ? fn.apply(out).then() : out.sendString(Mono.just("NOPE")))).wiretap(true).bindNow();
    assertThat(context).isNotNull();
    AtomicReference<String> m1 = new AtomicReference<>();
    AtomicReference<String> m2 = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(2);
    Connection client1 = TcpClient.create().port(context.port()).handle((in, out) -> {
        in.receive().asString().log("-----------------CLIENT1").subscribe(s -> {
            m1.set(s);
            latch.countDown();
        });
        return out.sendString(Mono.just("gogogo")).neverComplete();
    }).wiretap(true).connectNow();
    Connection client2 = TcpClient.create().port(context.port()).option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 1024, 65536)).handle((in, out) -> {
        in.receive().asString(StandardCharsets.UTF_8).take(2).reduceWith(String::new, String::concat).log("-----------------CLIENT2").subscribe(s -> {
            m2.set(s);
            latch.countDown();
        });
        return out.sendString(Mono.just("GOGOGO")).neverComplete();
    }).wiretap(true).connectNow();
    assertThat(client2).isNotNull();
    assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
    client1.disposeNow();
    client2.disposeNow();
    context.disposeNow();
    assertThat(m1.get()).isNotNull().isEqualTo("NOPE");
    assertThat(m2.get()).isNotNull().startsWith("This is an UTF-8 file that is larger than 1024 bytes. " + "It contains accents like é.").contains("1024 mark here ->").contains("<- 1024 mark here").endsWith("End of File");
}
Also used : SNIHostName(javax.net.ssl.SNIHostName) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) BiFunction(java.util.function.BiFunction) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) ConnectionObserver(reactor.netty.ConnectionObserver) Loggers(reactor.util.Loggers) SocketChannel(java.nio.channels.SocketChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) NettyPipeline(reactor.netty.NettyPipeline) Duration(java.time.Duration) Logger(reactor.util.Logger) Path(java.nio.file.Path) JsonObjectDecoder(io.netty.handler.codec.json.JsonObjectDecoder) LoopResources(reactor.netty.resources.LoopResources) ChannelGroup(io.netty.channel.group.ChannelGroup) FileSystem(java.nio.file.FileSystem) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ChannelBindException(reactor.netty.ChannelBindException) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) NettyOutbound(reactor.netty.NettyOutbound) Exceptions(reactor.core.Exceptions) DisposableServer(reactor.netty.DisposableServer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) SocketUtils(reactor.netty.SocketUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) Connection(reactor.netty.Connection) SslContext(io.netty.handler.ssl.SslContext) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) Files(java.nio.file.Files) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Publisher(org.reactivestreams.Publisher) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NetUtil(io.netty.util.NetUtil) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) SslProvider(io.netty.handler.ssl.SslProvider) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) NettyInbound(reactor.netty.NettyInbound) Timeout(org.junit.jupiter.api.Timeout) FileSystems(java.nio.file.FileSystems) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) DisposableServer(reactor.netty.DisposableServer) Connection(reactor.netty.Connection) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 38 with Connection

use of reactor.netty.Connection in project reactor-netty by reactor.

the class TcpServerTests method testHalfClosedConnection.

@Test
@SuppressWarnings("FutureReturnValueIgnored")
void testHalfClosedConnection() throws Exception {
    DisposableServer server = TcpServer.create().port(0).childOption(ChannelOption.ALLOW_HALF_CLOSURE, true).wiretap(true).handle((in, out) -> in.receive().asString().doOnNext(s -> {
        if (s.endsWith("257\n")) {
            out.sendString(Mono.just("END").delayElement(Duration.ofMillis(100))).then().subscribe();
        }
    }).then()).bindNow();
    Connection conn = TcpClient.create().remoteAddress(server::address).wiretap(true).connectNow();
    CountDownLatch latch = new CountDownLatch(1);
    conn.inbound().receive().asString().subscribe(s -> {
        if ("END".equals(s)) {
            latch.countDown();
        }
    });
    conn.outbound().sendString(Flux.range(1, 257).map(count -> count + "\n")).then().subscribe(null, null, // FutureReturnValueIgnored
    () -> ((io.netty.channel.socket.SocketChannel) conn.channel()).shutdownOutput());
    assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
    conn.disposeNow();
    server.disposeNow();
}
Also used : SNIHostName(javax.net.ssl.SNIHostName) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) BiFunction(java.util.function.BiFunction) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) ConnectionObserver(reactor.netty.ConnectionObserver) Loggers(reactor.util.Loggers) SocketChannel(java.nio.channels.SocketChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) NettyPipeline(reactor.netty.NettyPipeline) Duration(java.time.Duration) Logger(reactor.util.Logger) Path(java.nio.file.Path) JsonObjectDecoder(io.netty.handler.codec.json.JsonObjectDecoder) LoopResources(reactor.netty.resources.LoopResources) ChannelGroup(io.netty.channel.group.ChannelGroup) FileSystem(java.nio.file.FileSystem) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ChannelBindException(reactor.netty.ChannelBindException) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) NettyOutbound(reactor.netty.NettyOutbound) Exceptions(reactor.core.Exceptions) DisposableServer(reactor.netty.DisposableServer) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) SocketUtils(reactor.netty.SocketUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) Connection(reactor.netty.Connection) SslContext(io.netty.handler.ssl.SslContext) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) Files(java.nio.file.Files) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) Publisher(org.reactivestreams.Publisher) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NetUtil(io.netty.util.NetUtil) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) SslProvider(io.netty.handler.ssl.SslProvider) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) NettyInbound(reactor.netty.NettyInbound) Timeout(org.junit.jupiter.api.Timeout) FileSystems(java.nio.file.FileSystems) ConnectionObserver(reactor.netty.ConnectionObserver) DisposableServer(reactor.netty.DisposableServer) Connection(reactor.netty.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 39 with Connection

use of reactor.netty.Connection in project reactor-netty by reactor.

the class TcpServerTests method exposesRemoteAddress.

@Test
void exposesRemoteAddress() throws InterruptedException {
    final int port = SocketUtils.findAvailableTcpPort();
    final CountDownLatch latch = new CountDownLatch(1);
    DisposableServer server = TcpServer.create().port(port).handle((in, out) -> {
        in.withConnection(c -> {
            InetSocketAddress addr = (InetSocketAddress) c.address();
            assertThat(addr.getAddress()).as("remote address is not null").isNotNull();
            latch.countDown();
        });
        return Flux.never();
    }).wiretap(true).bindNow();
    assertThat(server).isNotNull();
    Connection client = TcpClient.create().port(port).handle((in, out) -> out.sendString(Flux.just("Hello World!"))).wiretap(true).connectNow();
    assertThat(client).isNotNull();
    assertThat(latch.await(5, TimeUnit.SECONDS)).as("Latch was counted down").isTrue();
    client.disposeNow();
    server.disposeNow();
}
Also used : DisposableServer(reactor.netty.DisposableServer) InetSocketAddress(java.net.InetSocketAddress) Connection(reactor.netty.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 40 with Connection

use of reactor.netty.Connection in project reactor-netty by reactor.

the class TcpServerTests method tcpServerHandlesJsonPojosOverSsl.

@Test
void tcpServerHandlesJsonPojosOverSsl() throws Exception {
    final CountDownLatch latch = new CountDownLatch(2);
    SslContext serverOptions = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(SslProvider.JDK).build();
    SslContext clientOptions = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(SslProvider.JDK).build();
    log.debug("Using SslContext: {}", clientOptions);
    final TcpServer server = TcpServer.create().host("localhost").secure(sslContextSpec -> sslContextSpec.sslContext(serverOptions));
    ObjectMapper m = new ObjectMapper();
    DisposableServer connectedServer = server.handle((in, out) -> {
        in.receive().asByteArray().map(bb -> {
            try {
                return m.readValue(bb, Pojo.class);
            } catch (IOException io) {
                throw Exceptions.propagate(io);
            }
        }).log("conn").subscribe(data -> {
            if ("John Doe".equals(data.getName())) {
                latch.countDown();
            }
        });
        return out.sendString(Mono.just("Hi")).neverComplete();
    }).wiretap(true).bindNow();
    assertThat(connectedServer).isNotNull();
    final TcpClient client = TcpClient.create().host("localhost").port(connectedServer.port()).secure(spec -> spec.sslContext(clientOptions));
    Connection connectedClient = client.handle((in, out) -> {
        // in
        in.receive().asString().log("receive").subscribe(data -> {
            if (data.equals("Hi")) {
                latch.countDown();
            }
        });
        // out
        return out.send(Flux.just(new Pojo("John" + " Doe")).map(s -> {
            try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                m.writeValue(os, s);
                return out.alloc().buffer().writeBytes(os.toByteArray());
            } catch (IOException ioe) {
                throw Exceptions.propagate(ioe);
            }
        })).neverComplete();
    }).wiretap(true).connectNow();
    assertThat(connectedClient).isNotNull();
    assertThat(latch.await(5, TimeUnit.SECONDS)).as("Latch was counted down").isTrue();
    connectedClient.disposeNow();
    connectedServer.disposeNow();
}
Also used : DisposableServer(reactor.netty.DisposableServer) Connection(reactor.netty.Connection) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CountDownLatch(java.util.concurrent.CountDownLatch) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SslContext(io.netty.handler.ssl.SslContext) Test(org.junit.jupiter.api.Test)

Aggregations

Connection (reactor.netty.Connection)137 Test (org.junit.jupiter.api.Test)69 CountDownLatch (java.util.concurrent.CountDownLatch)52 Duration (java.time.Duration)49 Mono (reactor.core.publisher.Mono)47 InetSocketAddress (java.net.InetSocketAddress)41 TimeUnit (java.util.concurrent.TimeUnit)39 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)38 LoopResources (reactor.netty.resources.LoopResources)38 ByteBuf (io.netty.buffer.ByteBuf)35 Flux (reactor.core.publisher.Flux)35 DisposableServer (reactor.netty.DisposableServer)35 DomainSocketAddress (io.netty.channel.unix.DomainSocketAddress)33 AtomicReference (java.util.concurrent.atomic.AtomicReference)32 List (java.util.List)31 IOException (java.io.IOException)30 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)30 ChannelOption (io.netty.channel.ChannelOption)29 Unpooled (io.netty.buffer.Unpooled)28 Charset (java.nio.charset.Charset)28