Search in sources :

Example 41 with DisposableServer

use of reactor.netty.DisposableServer 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 42 with DisposableServer

use of reactor.netty.DisposableServer 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 43 with DisposableServer

use of reactor.netty.DisposableServer 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)

Example 44 with DisposableServer

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

the class TcpServerTests method flushEvery5ElementsWithManualDecoding.

@Test
void flushEvery5ElementsWithManualDecoding() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Function<List<Pojo>, ByteBuf> jsonEncoder = pojo -> {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            mapper.writeValue(out, pojo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Unpooled.copiedBuffer(out.toByteArray());
    };
    Function<String, Pojo[]> jsonDecoder = s -> {
        try {
            return mapper.readValue(s, Pojo[].class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };
    CountDownLatch dataLatch = new CountDownLatch(10);
    DisposableServer server = TcpServer.create().handle((in, out) -> in.withConnection(c -> c.addHandler(new JsonObjectDecoder())).receive().asString().log("serve").map(jsonDecoder).concatMap(Flux::fromArray).window(5).concatMap(w -> out.send(w.collectList().map(jsonEncoder)))).wiretap(true).bindNow();
    assertThat(server).isNotNull();
    Connection client = TcpClient.create().port(server.port()).handle((in, out) -> {
        in.withConnection(c -> c.addHandler(new JsonObjectDecoder())).receive().asString().log("receive").map(jsonDecoder).concatMap(Flux::fromArray).subscribe(c -> dataLatch.countDown());
        return out.send(Flux.range(1, 10).map(it -> new Pojo("test" + it)).log("send").collectList().map(jsonEncoder)).neverComplete();
    }).wiretap(true).connectNow();
    assertThat(client).isNotNull();
    assertThat(dataLatch.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
    assertThat(dataLatch.getCount()).isEqualTo(0);
    server.disposeNow();
    client.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) Connection(reactor.netty.Connection) JsonObjectDecoder(io.netty.handler.codec.json.JsonObjectDecoder) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuf(io.netty.buffer.ByteBuf) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelBindException(reactor.netty.ChannelBindException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) DisposableServer(reactor.netty.DisposableServer) List(java.util.List) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.jupiter.api.Test)

Example 45 with DisposableServer

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

the class TcpServerTests method exposesNettyPipelineConfiguration.

@Test
void exposesNettyPipelineConfiguration() throws InterruptedException {
    final int port = SocketUtils.findAvailableTcpPort();
    final CountDownLatch latch = new CountDownLatch(2);
    final TcpClient client = TcpClient.create().port(port);
    BiFunction<? super NettyInbound, ? super NettyOutbound, ? extends Publisher<Void>> serverHandler = (in, out) -> {
        in.receive().asString().subscribe(data -> {
            log.info("data " + data + " on " + in);
            latch.countDown();
        });
        return Flux.never();
    };
    TcpServer server = TcpServer.create().doOnConnection(c -> c.addHandlerLast("codec", new LineBasedFrameDecoder(8 * 1024))).port(port);
    DisposableServer connected = server.handle(serverHandler).wiretap(true).bindNow();
    assertThat(connected).isNotNull();
    Connection clientContext = client.handle((in, out) -> out.sendString(Flux.just("Hello World!\n", "Hello 11!\n"))).wiretap(true).connectNow();
    assertThat(clientContext).isNotNull();
    assertThat(latch.await(10, TimeUnit.SECONDS)).as("Latch was counted down").isTrue();
    connected.disposeNow();
    clientContext.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) DisposableServer(reactor.netty.DisposableServer) Connection(reactor.netty.Connection) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Aggregations

DisposableServer (reactor.netty.DisposableServer)137 Mono (reactor.core.publisher.Mono)84 Test (org.junit.jupiter.api.Test)79 Duration (java.time.Duration)71 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)71 AtomicReference (java.util.concurrent.atomic.AtomicReference)68 Flux (reactor.core.publisher.Flux)68 Connection (reactor.netty.Connection)67 TimeUnit (java.util.concurrent.TimeUnit)65 LoopResources (reactor.netty.resources.LoopResources)60 List (java.util.List)58 CountDownLatch (java.util.concurrent.CountDownLatch)57 DomainSocketAddress (io.netty.channel.unix.DomainSocketAddress)56 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)55 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)54 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)54 InsecureTrustManagerFactory (io.netty.handler.ssl.util.InsecureTrustManagerFactory)53 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)53 Assumptions.assumeThat (org.assertj.core.api.Assumptions.assumeThat)53 StepVerifier (reactor.test.StepVerifier)53