Search in sources :

Example 41 with Connection

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

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

Example 43 with Connection

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

the class TcpServerTests method testEchoWithLineBasedFrameDecoder.

@Test
void testEchoWithLineBasedFrameDecoder() throws Exception {
    CountDownLatch latch = new CountDownLatch(2);
    DisposableServer server = TcpServer.create().port(0).doOnConnection(c -> c.addHandlerLast("codec", new LineBasedFrameDecoder(256))).handle((in, out) -> out.sendString(in.receive().asString().doOnNext(s -> {
        if ("4".equals(s)) {
            latch.countDown();
        }
    }).map(s -> s + "\n"))).bindNow();
    assertThat(server).isNotNull();
    Connection client = TcpClient.create().port(server.port()).doOnConnected(c -> c.addHandlerLast("codec", new LineBasedFrameDecoder(256))).handle((in, out) -> out.sendString(Flux.just("1\n", "2\n", "3\n", "4\n")).then(in.receive().asString().doOnNext(s -> {
        if ("4".equals(s)) {
            latch.countDown();
        }
    }).then())).connectNow();
    assertThat(client).isNotNull();
    assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
}
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)

Example 44 with Connection

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

the class TransportEventLoopMetricsTest method testEventLoopMetrics.

@Test
void testEventLoopMetrics() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    DisposableServer server = null;
    Connection client = null;
    LoopResources loop = null;
    try {
        loop = LoopResources.create(TransportEventLoopMetricsTest.class.getName(), 3, true);
        server = TcpServer.create().port(0).metrics(true).runOn(loop).doOnConnection(c -> {
            EventLoop eventLoop = c.channel().eventLoop();
            IntStream.range(0, 10).forEach(i -> eventLoop.execute(() -> {
            }));
            if (eventLoop instanceof SingleThreadEventExecutor) {
                SingleThreadEventExecutor singleThreadEventExecutor = (SingleThreadEventExecutor) eventLoop;
                String[] tags = new String[] { NAME, singleThreadEventExecutor.threadProperties().name() };
                assertThat(getGaugeValue(EVENT_LOOP_PREFIX + PENDING_TASKS, tags)).isEqualTo(10);
                latch.countDown();
            }
        }).wiretap(true).bindNow();
        assertThat(server).isNotNull();
        client = TcpClient.create().port(server.port()).wiretap(true).connectNow();
        assertThat(client).isNotNull();
        assertThat(latch.await(5, TimeUnit.SECONDS)).as("Did not find 10 pending tasks from meter").isTrue();
    } finally {
        if (client != null) {
            client.disposeNow();
        }
        if (server != null) {
            server.disposeNow();
        }
        if (loop != null) {
            loop.disposeLater().block(Duration.ofSeconds(10));
        }
    }
}
Also used : LoopResources(reactor.netty.resources.LoopResources) IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) EVENT_LOOP_PREFIX(reactor.netty.Metrics.EVENT_LOOP_PREFIX) SimpleMeterRegistry(io.micrometer.api.instrument.simple.SimpleMeterRegistry) SingleThreadEventExecutor(io.netty.util.concurrent.SingleThreadEventExecutor) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) NAME(reactor.netty.Metrics.NAME) EventLoop(io.netty.channel.EventLoop) Test(org.junit.jupiter.api.Test) TcpClient(reactor.netty.tcp.TcpClient) TimeUnit(java.util.concurrent.TimeUnit) PENDING_TASKS(reactor.netty.Metrics.PENDING_TASKS) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) MeterRegistry(io.micrometer.api.instrument.MeterRegistry) Duration(java.time.Duration) Metrics(io.micrometer.api.instrument.Metrics) TcpServer(reactor.netty.tcp.TcpServer) Connection(reactor.netty.Connection) DisposableServer(reactor.netty.DisposableServer) Gauge(io.micrometer.api.instrument.Gauge) EventLoop(io.netty.channel.EventLoop) DisposableServer(reactor.netty.DisposableServer) SingleThreadEventExecutor(io.netty.util.concurrent.SingleThreadEventExecutor) LoopResources(reactor.netty.resources.LoopResources) Connection(reactor.netty.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 45 with Connection

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

the class UdpServerTests method portBindingException.

@Test
void portBindingException() {
    Connection conn = UdpServer.create().port(0).bindNow(Duration.ofSeconds(30));
    try {
        UdpServer.create().bindAddress(conn::address).bindNow(Duration.ofSeconds(30));
        fail("illegal-success");
    } catch (ChannelBindException e) {
        assertThat(((InetSocketAddress) conn.address()).getPort()).isEqualTo(e.localPort());
        e.printStackTrace();
    }
    conn.disposeNow();
}
Also used : Connection(reactor.netty.Connection) ChannelBindException(reactor.netty.ChannelBindException) 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