Java Code Examples for reactor.netty.Connection#disposeNow()

The following examples show how to use reactor.netty.Connection#disposeNow() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UdpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public 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) {
		assertEquals(e.localPort(), ((InetSocketAddress) conn.address()).getPort());
		e.printStackTrace();
	}

	conn.disposeNow();
}
 
Example 2
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void readIdleDoesNotFireWhileDataIsBeingRead()
		throws InterruptedException, IOException {
	final CountDownLatch latch = new CountDownLatch(1);
	long start = System.currentTimeMillis();

	TcpClient client = TcpClient.create()
	                            .port(heartbeatServerPort);

	Connection s =
			client.handle((in, out) -> {
			            in.withConnection(c -> c.onReadIdle(200, latch::countDown));
			            return Flux.never();
			      })
			      .wiretap(true)
			      .connectNow();

	assertTrue(latch.await(5, TimeUnit.SECONDS));
	heartbeatServer.close();

	long duration = System.currentTimeMillis() - start;

	assertThat(duration, is(greaterThanOrEqualTo(200L)));
	s.disposeNow();
}
 
Example 3
Source File: UdpClientTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue192() {
	LoopResources resources = LoopResources.create("testIssue192");
	UdpServer server = UdpServer.create()
	                            .runOn(resources);
	UdpClient client = UdpClient.create()
	                            .runOn(resources);
	assertThat(Thread.getAllStackTraces().keySet().stream().noneMatch(t -> t.getName().startsWith("testIssue192"))).isTrue();

	Connection conn1 = server.bindNow();
	Connection conn2 = client.connectNow();

	assertThat(conn1).isNotNull();
	assertThat(conn2).isNotNull();
	assertThat(Thread.getAllStackTraces().keySet().stream().anyMatch(t -> t.getName().startsWith("testIssue192"))).isTrue();

	conn1.disposeNow();
	conn2.disposeNow();
	resources.dispose();
}
 
Example 4
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testTcpClient1ThreadAcquire() {

	LoopResources resources = LoopResources.create("test", 1, true);


	Connection client = TcpClient.create()
	                             .host("localhost")
	                             .port(echoServerPort)
	                             .runOn(resources)
	                             .wiretap(true)
	                             .connectNow();

	client.disposeNow();
	resources.dispose();

	assertThat("client was configured", client instanceof ChannelOperations);
}
 
Example 5
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void writeIdleDoesNotFireWhileDataIsBeingSent()
		throws InterruptedException {
	final CountDownLatch latch = new CountDownLatch(1);
	long start = System.currentTimeMillis();

	Connection client = TcpClient.create()
	                             .host("localhost")
	                             .port(echoServerPort)
	                             .handle((in, out) -> {
		                               log.debug("hello");
		                               out.withConnection(c -> c.onWriteIdle(500, latch::countDown));

		                               List<Publisher<Void>> allWrites =
				                               new ArrayList<>();
		                               for (int i = 0; i < 5; i++) {
			                               allWrites.add(out.sendString(Flux.just("a")
			                                                                .delayElements(Duration.ofMillis(750))));
		                               }
		                               return Flux.merge(allWrites);
	                               })
	                             .wiretap(true)
	                             .connectNow();

	log.debug("Started");

	assertTrue(latch.await(5, TimeUnit.SECONDS));

	long duration = System.currentTimeMillis() - start;

	assertThat(duration, is(greaterThanOrEqualTo(500L)));
	client.disposeNow();
}
 
Example 6
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void consumerSpecAssignsEventHandlers()
		throws InterruptedException {
	final CountDownLatch latch = new CountDownLatch(2);
	final CountDownLatch close = new CountDownLatch(1);
	final AtomicLong totalDelay = new AtomicLong();
	final long start = System.currentTimeMillis();

	TcpClient client =
			TcpClient.create()
			         .host("localhost")
			         .port(timeoutServerPort);

	Connection s =
			client.handle((in, out) -> {
			            in.withConnection(c -> c.onDispose(close::countDown));

			            out.withConnection(c -> c.onWriteIdle(200, () -> {
			                totalDelay.addAndGet(System.currentTimeMillis() - start);
			                latch.countDown();
			            }));

			            return Mono.delay(Duration.ofSeconds(1))
			                       .then()
			                       .log();
			      })
			      .wiretap(true)
			      .connectNow();

	assertTrue("latch was counted down", latch.await(5, TimeUnit.SECONDS));
	assertTrue("close was counted down", close.await(30, TimeUnit.SECONDS));
	assertThat("totalDelay was > 500ms", totalDelay.get(), greaterThanOrEqualTo(200L));

	s.disposeNow();
}
 
Example 7
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testCancelSend() throws InterruptedException {
	final CountDownLatch connectionLatch = new CountDownLatch(3);

	TcpClient tcpClient =
			TcpClient.newConnection()
			         .host("localhost")
	                 .port(echoServerPort);
	Connection c;

	c = tcpClient.handle((i, o) -> {
		o.sendObject(Mono.never()
		                 .doOnCancel(connectionLatch::countDown)
		                 .log("uno"))
		 .then()
		 .subscribe()
		 .dispose();

		Schedulers.parallel()
		          .schedule(() -> o.sendObject(Mono.never()
		                                           .doOnCancel(connectionLatch::countDown)
		                                           .log("dos"))
		                           .then()
		                           .subscribe()
		                           .dispose());

		o.sendObject(Mono.never()
		                 .doOnCancel(connectionLatch::countDown)
		                 .log("tres"))
		 .then()
		 .subscribe()
		 .dispose();

		return Mono.never();
	})
	             .connectNow();

	assertTrue("Cancel not propagated", connectionLatch.await(30, TimeUnit.SECONDS));
	c.disposeNow();
}
 
Example 8
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue825() throws Exception {
	disposableServer =
			HttpServer.create()
			          .port(0)
			          .handle((req, resp) -> resp.sendString(Mono.just("test")))
			          .wiretap(true)
			          .bindNow();

	DefaultFullHttpRequest request =
			new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");

	CountDownLatch latch = new CountDownLatch(1);

	Connection client =
			TcpClient.create()
			         .port(disposableServer.port())
			         .handle((in, out) -> {
			             in.withConnection(x -> x.addHandlerFirst(new HttpClientCodec()))
			               .receiveObject()
			               .ofType(DefaultHttpContent.class)
			               .as(ByteBufFlux::fromInbound)
			               // ReferenceCounted::release is deliberately invoked
			               // so that .release() in FluxReceive.drainReceiver will fail
			               .subscribe(ReferenceCounted::release, t -> latch.countDown(), null);

			             return out.sendObject(Flux.just(request))
			                       .neverComplete();
			         })
			         .wiretap(true)
			         .connectNow();

	assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();

	client.disposeNow();
}
 
Example 9
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testTcpServerWithDomainSockets() throws Exception {
	assumeTrue(LoopResources.hasNativeSupport());
	DisposableServer disposableServer =
			TcpServer.create()
			         .bindAddress(() -> new DomainSocketAddress("/tmp/test.sock"))
			         .wiretap(true)
			         .handle((in, out) -> out.send(in.receive().retain()))
			         .bindNow();

	Connection conn =
			TcpClient.create()
			         .remoteAddress(disposableServer::address)
			         .wiretap(true)
			         .connectNow();

	conn.outbound()
	    .sendString(Flux.just("1", "2", "3"))
	    .then()
	    .subscribe();

	CountDownLatch latch = new CountDownLatch(1);
	conn.inbound()
	    .receive()
	    .asString()
	    .doOnNext(s -> {
	        if (s.endsWith("3")) {
	            latch.countDown();
	        }
	    })
	    .subscribe();

	assertTrue(latch.await(30, TimeUnit.SECONDS));

	conn.disposeNow();
	disposableServer.disposeNow();
}
 
Example 10
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue462() throws InterruptedException {

	final CountDownLatch countDownLatch = new CountDownLatch(1);

	DisposableServer server = TcpServer.create()
	                                   .port(0)
	                                   .handle((in, out) -> {
	                                       in.receive()
	                                         .log("channel")
	                                         .subscribe(trip -> countDownLatch.countDown());
	                                       return Flux.never();
	                                   })
	                                   .wiretap(true)
	                                   .bindNow();

	assertNotNull(server);

	System.out.println("PORT +" + server.port());

	Connection client = TcpClient.create()
	                             .port(server.port())
	                             .handle((in, out) -> out.sendString(Flux.just("test")))
	                             .wiretap(true)
	                             .connectNow();

	assertNotNull(client);

	assertThat("Latch was counted down", countDownLatch.await(5, TimeUnit.SECONDS));

	client.disposeNow();
	server.disposeNow();
}
 
Example 11
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public 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();
	        assertNotNull("remote address is not null", addr.getAddress());
	        latch.countDown();
	    });

		return Flux.never();
	                                   })
	                                   .wiretap(true)
	                                   .bindNow();

	assertNotNull(server);

	Connection client = TcpClient.create().port(port)
	                             .handle((in, out) -> out.sendString(Flux.just("Hello World!")))
	                             .wiretap(true)
	                             .connectNow();

	assertNotNull(client);

	assertTrue("Latch was counted down", latch.await(5, TimeUnit.SECONDS));

	client.disposeNow();
	server.disposeNow();
}
 
Example 12
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetryOnDifferentAddress() throws Exception {
	DisposableServer server =
			TcpServer.create()
			         .port(0)
			         .wiretap(true)
			         .handle((req, res) -> res.sendString(Mono.just("test")))
			         .bindNow();

	final CountDownLatch latch = new CountDownLatch(1);

	Supplier<SocketAddress> addressSupplier = new Supplier<SocketAddress>() {
		int i = 2;

		@Override
		public SocketAddress get() {
			return new InetSocketAddress("localhost", server.port() + i--);
		}
	};

	Connection  conn =
			TcpClient.create()
			         .remoteAddress(addressSupplier)
			         .doOnConnected(connection -> latch.countDown())
			         .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100)
			         .handle((in, out) -> Mono.never())
			         .wiretap(true)
			         .connect()
			         .retry()
			         .block(Duration.ofSeconds(30));
	assertNotNull(conn);

	assertTrue(latch.await(30, TimeUnit.SECONDS));

	conn.disposeNow();
	server.disposeNow();
}
 
Example 13
Source File: BlockingConnectionTest.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void simpleServerFromAsyncServer() throws InterruptedException {
	DisposableServer simpleServer =
			TcpServer.create()
			         .handle((in, out) -> out
					         .sendString(
							         in.receive()
							           .asString()
							           .takeUntil(s -> s.endsWith("CONTROL"))
							           .map(s -> "ECHO: " + s.replaceAll("CONTROL", ""))
							           .concatWith(Mono.just("DONE"))
					         )
					         .neverComplete()
			         )
			         .wiretap(true)
			         .bindNow();

	InetSocketAddress address = (InetSocketAddress) simpleServer.address();

	AtomicReference<List<String>> data1 = new AtomicReference<>();
	AtomicReference<List<String>> data2 = new AtomicReference<>();

	Connection simpleClient1 =
			TcpClient.create().port(address.getPort())
			         .handle((in, out) -> out.sendString(Flux.just("Hello", "World", "CONTROL"))
			                                 .then(in.receive()
			                                        .asString()
			                                        .takeUntil(s -> s.endsWith("DONE"))
			                                        .map(s -> s.replaceAll("DONE", ""))
			                                        .filter(s -> !s.isEmpty())
			                                        .collectList()
			                                        .doOnNext(data1::set)
			                                        .doOnNext(System.err::println)
			                                        .then()))
			         .wiretap(true)
			         .connectNow();

	Connection simpleClient2 =
			TcpClient.create()
			         .port(address.getPort())
			         .handle((in, out) -> out.sendString(Flux.just("How", "Are", "You?", "CONTROL"))
			                                 .then(in.receive()
			                                        .asString()
			                                        .takeUntil(s -> s.endsWith("DONE"))
			                                        .map(s -> s.replaceAll("DONE", ""))
			                                        .filter(s -> !s.isEmpty())
			                                        .collectList()
			                                        .doOnNext(data2::set)
			                                        .doOnNext(System.err::println)
			                                        .then()))
			         .wiretap(true)
			         .connectNow();

	Thread.sleep(100);
	System.err.println("STOPPING 1");
	simpleClient1.disposeNow();

	System.err.println("STOPPING 2");
	simpleClient2.disposeNow();

	System.err.println("STOPPING SERVER");
	simpleServer.disposeNow();

	assertThat(data1.get())
			.allSatisfy(s -> assertThat(s).startsWith("ECHO: "));
	assertThat(data2.get())
			.allSatisfy(s -> assertThat(s).startsWith("ECHO: "));

	assertThat(data1.get()
	                .toString()
	                .replaceAll("ECHO: ", "")
	                .replaceAll(", ", ""))
			.isEqualTo("[HelloWorld]");
	assertThat(data2.get()
	                .toString()
	                .replaceAll("ECHO: ", "")
	                .replaceAll(", ", ""))
	.isEqualTo("[HowAreYou?]");
}
 
Example 14
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void httpPipelining() throws Exception {

	AtomicInteger i = new AtomicInteger();

	disposableServer = HttpServer.create()
	                             .port(0)
	                             .handle((req, resp) ->
	                                     resp.header(HttpHeaderNames.CONTENT_LENGTH, "1")
	                                         .sendString(Mono.just(i.incrementAndGet())
	                                                         .flatMap(d ->
	                                                                 Mono.delay(Duration.ofSeconds(4 - d))
	                                                                     .map(x -> d + "\n"))))
	                             .wiretap(true)
	                             .bindNow();

	DefaultFullHttpRequest request =
			new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
			                           HttpMethod.GET,
			                           "/plaintext");

	CountDownLatch latch = new CountDownLatch(6);

	Connection client =
			TcpClient.create()
			         .port(disposableServer.port())
			         .handle((in, out) -> {
			                 in.withConnection(x ->
			                         x.addHandlerFirst(new HttpClientCodec()))
			                   .receiveObject()
			                   .ofType(DefaultHttpContent.class)
			                   .as(ByteBufFlux::fromInbound)
			                   .asString()
			                   .log()
			                   .map(Integer::parseInt)
			                   .subscribe(d -> {
			                       for (int x = 0; x < d; x++) {
			                           latch.countDown();
			                       }
			                   });

			                 return out.sendObject(Flux.just(request.retain(),
			                                                 request.retain(),
			                                                 request.retain()))
			                           .neverComplete();
			         })
			         .wiretap(true)
			         .connectNow();

	assertThat(latch.await(45, TimeUnit.SECONDS)).isTrue();

	client.disposeNow();
}
 
Example 15
Source File: ConnectionInfoTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void proxyProtocolAuto() throws InterruptedException {
	String remoteAddress = "202.112.144.236";
	ArrayBlockingQueue<String> resultQueue = new ArrayBlockingQueue<>(1);

	Consumer<HttpServerRequest> requestConsumer = serverRequest -> {
		String remoteAddrFromRequest = serverRequest.remoteAddress().getHostString();
		resultQueue.add(remoteAddrFromRequest);
	};

	this.connection =
			HttpServer.create()
			          .port(0)
			          .proxyProtocol(ProxyProtocolSupportType.AUTO)
			          .handle((req, res) -> {
			              try {
			                  requestConsumer.accept(req);
			                  return res.status(200)
			                            .sendString(Mono.just("OK"));
			              }
			              catch (Throwable e) {
			                  return res.status(500)
			                            .sendString(Mono.just(e.getMessage()));
			              }
			          })
			          .wiretap(true)
			          .bindNow();

	Connection clientConn =
			TcpClient.create()
			         .port(this.connection.port())
			         .connectNow();

	ByteBuf proxyProtocolMsg = clientConn.channel()
	                                     .alloc()
	                                     .buffer();
	proxyProtocolMsg.writeCharSequence("PROXY TCP4 " + remoteAddress + " 10.210.12.10 5678 80\r\n",
			Charset.defaultCharset());
	proxyProtocolMsg.writeCharSequence("GET /test HTTP/1.1\r\nHost: a.example.com\r\n\r\n",
			Charset.defaultCharset());
	clientConn.channel()
	          .writeAndFlush(proxyProtocolMsg)
	          .addListener(f -> {
	              if (!f.isSuccess()) {
	                  fail("Writing proxyProtocolMsg was not successful");
	              }
	          });

	assertThat(resultQueue.poll(5, TimeUnit.SECONDS)).isEqualTo(remoteAddress);

	clientConn.disposeNow();

	clientConn =
			TcpClient.create()
			          .port(this.connection.port())
			          .connectNow();

	// Send a http request without proxy protocol in a new connection,
	// server should support this when proxyProtocol is set to ProxyProtocolSupportType.AUTO
	ByteBuf httpMsg = clientConn.channel()
	                            .alloc()
	                            .buffer();
	httpMsg.writeCharSequence("GET /test HTTP/1.1\r\nHost: a.example.com\r\n\r\n",
			Charset.defaultCharset());
	clientConn.channel()
	          .writeAndFlush(httpMsg)
	          .addListener(f -> {
	              if (!f.isSuccess()) {
	                  fail("Writing proxyProtocolMsg was not successful");
	              }
	          });

	assertThat(resultQueue.poll(5, TimeUnit.SECONDS))
			.containsPattern("^0:0:0:0:0:0:0:1(%\\w*)?|127.0.0.1$");
}
 
Example 16
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void testIssue585_1() throws Exception {
	DisposableServer server =
			TcpServer.create()
			         .port(0)
			         .handle((req, res) -> res.send(req.receive()
			                                           .retain()))
			         .wiretap(true)
			         .bindNow();

	CountDownLatch latch = new CountDownLatch(1);

	byte[] bytes = "test".getBytes(Charset.defaultCharset());
	ByteBuf b1 = Unpooled.wrappedBuffer(bytes);
	ByteBuf b2 = Unpooled.wrappedBuffer(bytes);
	ByteBuf b3 = Unpooled.wrappedBuffer(bytes);

	WeakReference<ByteBuf> refCheck1 = new WeakReference<>(b1);
	WeakReference<ByteBuf> refCheck2 = new WeakReference<>(b2);
	WeakReference<ByteBuf> refCheck3 = new WeakReference<>(b3);

	Connection conn =
			TcpClient.create()
			         .remoteAddress(server::address)
			         .wiretap(true)
			         .connectNow();

	NettyOutbound out = conn.outbound();

	Flux.concatDelayError(
	        out.sendObject(Mono.error(new RuntimeException("test")))
	           .sendObject(b1)
	           .then(),
	        out.sendObject(Mono.error(new RuntimeException("test")))
	           .sendObject(b2)
	           .then(),
	        out.sendObject(Mono.error(new RuntimeException("test")))
	           .sendObject(b3)
	           .then())
	    .doOnError(t -> latch.countDown())
	    .subscribe(conn.disposeSubscriber());

	Assertions.assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();

	Assertions.assertThat(b1.refCnt()).isEqualTo(0);
	b1 = null;
	checkReference(refCheck1);

	Assertions.assertThat(b2.refCnt()).isEqualTo(0);
	b2 = null;
	checkReference(refCheck2);

	Assertions.assertThat(b3.refCnt()).isEqualTo(0);
	b3 = null;
	checkReference(refCheck3);

	server.disposeNow();
	conn.disposeNow();
}
 
Example 17
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testBootstrap() {
	DisposableServer server =
			TcpServer.create()
			         .port(0)
			         .handle((req, res) -> res.send(req.receive()
			                                           .retain()))
			         .wiretap(true)
			         .bindNow();

	AtomicInteger invoked = new AtomicInteger();
	Connection conn =
			TcpClient.create()
			         .bootstrap(b ->
			             b.attr(AttributeKey.valueOf("testBootstrap"), "testBootstrap")
			              .group(new NioEventLoopGroup())
			              .option(ChannelOption.valueOf("testBootstrap"), "testBootstrap")
			              .remoteAddress(server.address())
			              .resolver(DefaultAddressResolverGroup.INSTANCE)
			              .handler(new ChannelInboundHandlerAdapter() {
			                  @Override
			                  public void channelActive(ChannelHandlerContext ctx) throws Exception {
			                      invoked.set(1);
			                      super.channelActive(ctx);
			                  }
			              }))
			         .connectNow();

	conn.outbound()
	    .sendString(Mono.just("testBootstrap"))
	    .then()
	    .subscribe();

	String result =
			conn.inbound()
			    .receive()
			    .asString()
			    .blockFirst();

	assertEquals("testBootstrap", result);
	assertEquals(1, invoked.get());

	conn.disposeNow();
	server.disposeNow();
}
 
Example 18
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public 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();

	assertNotNull(connected);

	Connection clientContext =
			client.handle((in, out) -> out.sendString(Flux.just("Hello World!\n", "Hello 11!\n")))
			      .wiretap(true)
			      .connectNow();

	assertNotNull(clientContext);

	assertTrue("Latch was counted down", latch.await(10, TimeUnit.SECONDS));

	connected.disposeNow();
	clientContext.disposeNow();
}
 
Example 19
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void tcpServerHandlesJsonPojosOverSsl() throws Exception {
	final CountDownLatch latch = new CountDownLatch(2);

	SelfSignedCertificate cert = new SelfSignedCertificate();
	SslContextBuilder serverOptions = SslContextBuilder.forServer(cert.certificate(), cert.privateKey())
	                                                   .sslProvider(SslProvider.JDK);
	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();

	assertNotNull(connectedServer);

	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();

	assertNotNull(connectedClient);

	assertTrue("Latch was counted down", latch.await(5, TimeUnit.SECONDS));

	connectedClient.disposeNow();
	connectedServer.disposeNow();
}
 
Example 20
Source File: UdpServerTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public 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));
	Assertions.assertThat(server).isNotNull();

	assertThat("latch was counted down", latch.await(10, TimeUnit.SECONDS));
	server.disposeNow();
}