Search in sources :

Example 46 with Connection

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

the class UdpServerTests method supportsReceivingDatagrams.

@Test
void supportsReceivingDatagrams() throws InterruptedException {
    final Random rndm = new Random();
    final int port = SocketUtils.findAvailableUdpPort();
    final CountDownLatch latch = new CountDownLatch(4);
    final Connection server = UdpServer.create().port(port).handle((in, out) -> {
        in.receive().asByteArray().log().subscribe(bytes -> {
            if (bytes.length == 1024) {
                latch.countDown();
            }
        });
        return Flux.never();
    }).bind().doOnSuccess(v -> {
        try {
            DatagramChannel udp = DatagramChannel.open();
            udp.configureBlocking(true);
            udp.connect(v.address());
            byte[] data = new byte[1024];
            rndm.nextBytes(data);
            for (int i = 0; i < 4; i++) {
                udp.write(ByteBuffer.wrap(data));
            }
            udp.close();
        } catch (IOException e) {
            log.error("", e);
        }
    }).block(Duration.ofSeconds(30));
    assertThat(server).isNotNull();
    assertThat(latch.await(10, TimeUnit.SECONDS)).as("latch was counted down").isTrue();
    server.disposeNow();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) StepVerifier(reactor.test.StepVerifier) ChannelOption(io.netty.channel.ChannelOption) Enumeration(java.util.Enumeration) SocketUtils(reactor.netty.SocketUtils) DatagramChannel(java.nio.channels.DatagramChannel) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Random(java.util.Random) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) SocketException(java.net.SocketException) Loggers(reactor.util.Loggers) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) Duration(java.time.Duration) Logger(reactor.util.Logger) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) InternetProtocolFamily(io.netty.channel.socket.InternetProtocolFamily) Schedulers(reactor.core.scheduler.Schedulers) Connection(reactor.netty.Connection) ExecutorService(java.util.concurrent.ExecutorService) LoopResources(reactor.netty.resources.LoopResources) Collection(java.util.Collection) NetworkInterface(java.net.NetworkInterface) NetUtil(io.netty.util.NetUtil) IOException(java.io.IOException) Inet4Address(java.net.Inet4Address) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) ChannelBindException(reactor.netty.ChannelBindException) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) AfterEach(org.junit.jupiter.api.AfterEach) Assertions.fail(org.assertj.core.api.Assertions.fail) MulticastSocket(java.net.MulticastSocket) DatagramPacket(java.net.DatagramPacket) Random(java.util.Random) Connection(reactor.netty.Connection) DatagramChannel(java.nio.channels.DatagramChannel) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 47 with Connection

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

the class TcpResourcesTest method blockShouldFail.

@Test
void blockShouldFail() throws InterruptedException {
    final int port = SocketUtils.findAvailableTcpPort();
    final CountDownLatch latch = new CountDownLatch(2);
    DisposableServer server = TcpServer.create().port(port).handle((in, out) -> {
        try {
            in.receive().blockFirst();
        } catch (RuntimeException e) {
            latch.countDown();
            throw e;
        }
        return Flux.never();
    }).bindNow();
    Connection client = TcpClient.newConnection().port(port).handle((in, out) -> {
        try {
            out.sendString(Flux.just("Hello World!")).then().block();
        } catch (RuntimeException e) {
            latch.countDown();
            throw e;
        }
        return Mono.never();
    }).connectNow();
    assertThat(latch.await(5, TimeUnit.SECONDS)).as("latch was counted down").isTrue();
    client.dispose();
    server.disposeNow();
}
Also used : LoopResources(reactor.netty.resources.LoopResources) BeforeEach(org.junit.jupiter.api.BeforeEach) EventLoopGroup(io.netty.channel.EventLoopGroup) SocketAddress(java.net.SocketAddress) SocketUtils(reactor.netty.SocketUtils) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Mono(reactor.core.publisher.Mono) Supplier(java.util.function.Supplier) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) ConnectionObserver(reactor.netty.ConnectionObserver) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) TransportConfig(reactor.netty.transport.TransportConfig) Duration(java.time.Duration) Connection(reactor.netty.Connection) ConnectionProvider(reactor.netty.resources.ConnectionProvider) DisposableServer(reactor.netty.DisposableServer) DisposableServer(reactor.netty.DisposableServer) Connection(reactor.netty.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Example 48 with Connection

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

the class HttpServerTests method testCancelConnectionCloseForWebSocketServer.

@Test
void testCancelConnectionCloseForWebSocketServer() throws Exception {
    AtomicReference<WebSocketCloseStatus> statusServer = new AtomicReference<>();
    AtomicReference<WebSocketCloseStatus> statusClient = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(2);
    disposableServer = createServer().handle((req, resp) -> resp.sendWebsocket((in, out) -> {
        in.receiveCloseStatus().doOnNext(o -> {
            statusServer.set(o);
            latch.countDown();
        }).subscribe();
        in.withConnection(Connection::dispose);
        return Mono.never();
    })).bindNow();
    createClient(disposableServer.port()).websocket().uri("/").handle((in, out) -> {
        in.receiveCloseStatus().doOnNext(o -> {
            statusClient.set(o);
            latch.countDown();
        }).subscribe();
        return Mono.never();
    }).subscribe();
    assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();
    assertThat(statusClient.get()).isNotNull().isEqualTo(WebSocketCloseStatus.EMPTY);
    assertThat(statusServer.get()).isNotNull().isEqualTo(WebSocketCloseStatus.ABNORMAL_CLOSURE);
}
Also used : AttributeKey(io.netty.util.AttributeKey) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) StepVerifier(reactor.test.StepVerifier) SNIHostName(javax.net.ssl.SNIHostName) AbortedException(reactor.netty.channel.AbortedException) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) HttpMessage(io.netty.handler.codec.http.HttpMessage) ByteBufHolder(io.netty.buffer.ByteBufHolder) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TcpClient(reactor.netty.tcp.TcpClient) ConnectionObserver(reactor.netty.ConnectionObserver) Future(java.util.concurrent.Future) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) BeforeAll(org.junit.jupiter.api.BeforeAll) Duration(java.time.Duration) DEFAULT_FORM_DECODER_SPEC(reactor.netty.http.server.HttpServerFormDecoderProvider.DEFAULT_FORM_DECODER_SPEC) Path(java.nio.file.Path) LoopResources(reactor.netty.resources.LoopResources) HttpObjectDecoder(io.netty.handler.codec.http.HttpObjectDecoder) HttpRequest(io.netty.handler.codec.http.HttpRequest) Context(reactor.util.context.Context) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) Assertions.fail(org.assertj.core.api.Assertions.fail) NettyOutbound(reactor.netty.NettyOutbound) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) GZIPOutputStream(java.util.zip.GZIPOutputStream) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) HttpClient(reactor.netty.http.client.HttpClient) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ChannelOption(io.netty.channel.ChannelOption) HttpProtocol(reactor.netty.http.HttpProtocol) Nullable(reactor.util.annotation.Nullable) ArrayList(java.util.ArrayList) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ValueSource(org.junit.jupiter.params.provider.ValueSource) PrematureCloseException(reactor.netty.http.client.PrematureCloseException) SslContext(io.netty.handler.ssl.SslContext) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) Field(java.lang.reflect.Field) ReferenceCounted(io.netty.util.ReferenceCounted) Channel(io.netty.channel.Channel) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultEventExecutor(io.netty.util.concurrent.DefaultEventExecutor) Flux(reactor.core.publisher.Flux) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) FutureMono(reactor.netty.FutureMono) Paths(java.nio.file.Paths) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) ConnectionProvider(reactor.netty.resources.ConnectionProvider) ServerCookieEncoder(io.netty.handler.codec.http.cookie.ServerCookieEncoder) HttpUtil(io.netty.handler.codec.http.HttpUtil) SocketAddress(java.net.SocketAddress) Http11SslContextSpec(reactor.netty.http.Http11SslContextSpec) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) URISyntaxException(java.net.URISyntaxException) BiFunction(java.util.function.BiFunction) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Http2SslContextSpec(reactor.netty.http.Http2SslContextSpec) TimeoutException(java.util.concurrent.TimeoutException) BaseHttpTest(reactor.netty.BaseHttpTest) Random(java.util.Random) Unpooled(io.netty.buffer.Unpooled) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) TransportConfig(reactor.netty.transport.TransportConfig) ServerCookieDecoder(io.netty.handler.codec.http.cookie.ServerCookieDecoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteBufFlux(reactor.netty.ByteBufFlux) NettyPipeline(reactor.netty.NettyPipeline) MethodSource(org.junit.jupiter.params.provider.MethodSource) ChannelGroup(io.netty.channel.group.ChannelGroup) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SignalType(reactor.core.publisher.SignalType) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ChannelBindException(reactor.netty.ChannelBindException) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) DisposableServer(reactor.netty.DisposableServer) HttpVersion(io.netty.handler.codec.http.HttpVersion) Tuple3(reactor.util.function.Tuple3) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WebSocketCloseStatus(io.netty.handler.codec.http.websocketx.WebSocketCloseStatus) Tuple2(reactor.util.function.Tuple2) HttpClientRequest(reactor.netty.http.client.HttpClientRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SniCompletionEvent(io.netty.handler.ssl.SniCompletionEvent) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) Connection(reactor.netty.Connection) ExecutorService(java.util.concurrent.ExecutorService) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpMethod(io.netty.handler.codec.http.HttpMethod) CertificateException(java.security.cert.CertificateException) TimeUnit(java.util.concurrent.TimeUnit) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) TcpServer(reactor.netty.tcp.TcpServer) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) Comparator(java.util.Comparator) Timeout(org.junit.jupiter.api.Timeout) WebSocketCloseStatus(io.netty.handler.codec.http.websocketx.WebSocketCloseStatus) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) BaseHttpTest(reactor.netty.BaseHttpTest) Test(org.junit.jupiter.api.Test)

Example 49 with Connection

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

the class Http2PoolTest method maxLifeTimeMaxConnectionsReached.

@Test
void maxLifeTimeMaxConnectionsReached() throws Exception {
    PoolBuilder<Connection, PoolConfig<Connection>> poolBuilder = PoolBuilder.from(Mono.fromSupplier(() -> {
        Channel channel = new EmbeddedChannel(new TestChannelId(), Http2FrameCodecBuilder.forClient().build());
        return Connection.from(channel);
    })).idleResourceReuseLruOrder().maxPendingAcquireUnbounded().sizeBetween(0, 1);
    Http2Pool http2Pool = poolBuilder.build(config -> new Http2Pool(config, 10));
    Connection connection = null;
    try {
        PooledRef<Connection> acquired1 = http2Pool.acquire().block();
        assertThat(acquired1).isNotNull();
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(1);
        assertThat(http2Pool.connections.size()).isEqualTo(1);
        connection = acquired1.poolable();
        Thread.sleep(10);
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(1);
        assertThat(http2Pool.connections.size()).isEqualTo(1);
        http2Pool.acquire(Duration.ofMillis(10)).as(StepVerifier::create).expectError(PoolAcquireTimeoutException.class).verify(Duration.ofSeconds(1));
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(1);
        assertThat(http2Pool.connections.size()).isEqualTo(1);
        acquired1.invalidate().block();
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(0);
        assertThat(http2Pool.connections.size()).isEqualTo(0);
    } finally {
        if (connection != null) {
            ((EmbeddedChannel) connection.channel()).finishAndReleaseAll();
            connection.dispose();
        }
    }
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) Connection(reactor.netty.Connection) PoolConfig(reactor.netty.internal.shaded.reactor.pool.PoolConfig) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) PoolAcquireTimeoutException(reactor.netty.internal.shaded.reactor.pool.PoolAcquireTimeoutException) StepVerifier(reactor.test.StepVerifier) Test(org.junit.jupiter.api.Test)

Example 50 with Connection

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

the class Http2PoolTest method acquireInvalidate.

@Test
void acquireInvalidate() {
    EmbeddedChannel channel = new EmbeddedChannel(Http2FrameCodecBuilder.forClient().build(), new Http2MultiplexHandler(new ChannelHandlerAdapter() {
    }));
    PoolBuilder<Connection, PoolConfig<Connection>> poolBuilder = PoolBuilder.from(Mono.just(Connection.from(channel))).idleResourceReuseLruOrder().maxPendingAcquireUnbounded().sizeBetween(0, 1);
    InstrumentedPool<Connection> http2Pool = poolBuilder.build(config -> new Http2Pool(config, -1));
    try {
        List<PooledRef<Connection>> acquired = new ArrayList<>();
        http2Pool.acquire().subscribe(acquired::add);
        http2Pool.acquire().subscribe(acquired::add);
        http2Pool.acquire().subscribe(acquired::add);
        assertThat(acquired).hasSize(3);
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(3);
        for (PooledRef<Connection> slot : acquired) {
            slot.invalidate().block(Duration.ofSeconds(1));
        }
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(0);
        for (PooledRef<Connection> slot : acquired) {
            // second invalidate() should be ignored and ACQUIRED size should remain the same
            slot.invalidate().block(Duration.ofSeconds(1));
        }
        assertThat(http2Pool.metrics().acquiredSize()).isEqualTo(0);
    } finally {
        channel.finishAndReleaseAll();
        Connection.from(channel).dispose();
    }
}
Also used : Connection(reactor.netty.Connection) ArrayList(java.util.ArrayList) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerAdapter(io.netty.channel.ChannelHandlerAdapter) Http2MultiplexHandler(io.netty.handler.codec.http2.Http2MultiplexHandler) PoolConfig(reactor.netty.internal.shaded.reactor.pool.PoolConfig) PooledRef(reactor.netty.internal.shaded.reactor.pool.PooledRef) 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