reactor.netty.tcp.TcpServer Java Examples

The following examples show how to use reactor.netty.tcp.TcpServer. 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: HttpClientTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void prematureCancel() {
	FluxIdentityProcessor<Void> signal = Processors.more().multicastNoBackpressure();
	disposableServer =
			TcpServer.create()
			         .host("localhost")
			         .port(0)
			         .handle((in, out) -> {
			             signal.onComplete();
			             return out.withConnection(c -> c.addHandlerFirst(new HttpResponseEncoder()))
			                       .sendObject(Mono.delay(Duration.ofSeconds(2))
			                                       .map(t -> new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
			                                                                             HttpResponseStatus.PROCESSING)))
			                       .neverComplete();
			         })
			         .wiretap(true)
			         .bindNow(Duration.ofSeconds(30));

	StepVerifier.create(
			createHttpClientForContextWithAddress()
			        .get()
			        .uri("/")
			        .responseContent()
			        .timeout(signal))
			    .verifyError(TimeoutException.class);
}
 
Example #2
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testTcpConfiguration_2() throws Exception {
	CountDownLatch latch = new CountDownLatch(10);
	LoopResources loop = LoopResources.create("testTcpConfiguration");
	ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	doTestTcpConfiguration(
			HttpServer.from(configureTcpServer(TcpServer.create(), loop, group, latch)),
			HttpClient.from(configureTcpClient(TcpClient.create(), loop, group, latch))
	);

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

	FutureMono.from(group.close())
	          .then(loop.disposeLater())
	          .block(Duration.ofSeconds(30));
}
 
Example #3
Source File: DiscardServer.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	TcpServer server =
			TcpServer.create()
			         .port(PORT)
			         .wiretap(WIRETAP)
			         .handle((in, out) -> {
			             // Discards the incoming data and releases the buffers
			             in.receive().subscribe();
			             return out.neverComplete();
			         });

	if (SECURE) {
		SelfSignedCertificate ssc = new SelfSignedCertificate();
		server = server.secure(
				spec -> spec.sslContext(SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())));
	}

	server.bindNow()
	      .onDispose()
	      .block();
}
 
Example #4
Source File: EchoServer.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	TcpServer server =
			TcpServer.create()
			         .port(PORT)
			         .wiretap(WIRETAP)
			         .handle((in, out) -> out.send(in.receive().retain()));

	if (SECURE) {
		SelfSignedCertificate ssc = new SelfSignedCertificate();
		server = server.secure(
				spec -> spec.sslContext(SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())));
	}

	server.bindNow()
	      .onDispose()
	      .block();
}
 
Example #5
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
private TcpServer configureTcpServer(TcpServer tcp, LoopResources loop, ChannelGroup group, CountDownLatch latch) {
	return tcp.wiretap(true)
	          .host("localhost")
	          .runOn(loop)
	          .channelGroup(group)
	          .doOnBound(s -> latch.countDown())
	          .doOnConnection(c -> latch.countDown())
	          .doOnUnbound(s -> latch.countDown())
	          .handle((req, res) -> res.send(req.receive().retain()))
	          .noSSL()
	          .port(0)
	          .attr(AttributeKey.valueOf("testTcpConfiguration"), "testTcpConfiguration")
	          .option(ChannelOption.valueOf("testTcpConfiguration"), "testTcpConfiguration")
	          .childAttr(AttributeKey.valueOf("testTcpConfiguration"), "testTcpConfiguration")
	          .childOption(ChannelOption.valueOf("testTcpConfiguration"), "testTcpConfiguration")
	          .observe((conn, state) -> latch.countDown())
	          .childObserve((conn, state) -> latch.countDown())
	          .doOnChannelInit((observer, channel, address) -> latch.countDown());
}
 
Example #6
Source File: TcpUriHandler.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<ServerTransport<?>> buildServer(URI uri) {
  Objects.requireNonNull(uri, "uri must not be null");

  if (!SCHEME.equals(uri.getScheme())) {
    return Optional.empty();
  }

  return Optional.of(
      TcpServerTransport.create(TcpServer.create().host(uri.getHost()).port(uri.getPort())));
}
 
Example #7
Source File: TcpServerTransportTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("create throws NullPointerException with null server")
@Test
void createNullTcpClient() {
  assertThatNullPointerException()
      .isThrownBy(() -> TcpServerTransport.create((TcpServer) null))
      .withMessage("server must not be null");
}
 
Example #8
Source File: StatsdMeterRegistryPublishTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private DisposableChannel startServer(StatsdProtocol protocol, int port) {
    if (protocol == StatsdProtocol.UDP) {
        return UdpServer.create()
                .host("localhost")
                .port(port)
                .handle((in, out) ->
                        in.receive().asString()
                                .flatMap(packet -> {
                                    serverLatch.countDown();
                                    return Flux.never();
                                }))
                .doOnBound((server) -> bound = true)
                .doOnUnbound((server) -> bound = false)
                .wiretap(true)
                .bindNow(Duration.ofSeconds(2));
    } else if (protocol == StatsdProtocol.TCP) {
        AtomicReference<DisposableChannel> channel = new AtomicReference<>();
        return TcpServer.create()
                .host("localhost")
                .port(port)
                .handle((in, out) ->
                        in.receive().asString()
                                .flatMap(packet -> {
                                    IntStream.range(0, packet.split("my.counter").length - 1).forEach(i -> serverLatch.countDown());
                                    in.withConnection(channel::set);
                                    return Flux.never();
                                }))
                .doOnBound((server) -> bound = true)
                .doOnUnbound((server) -> {
                    bound = false;
                    channel.get().dispose();
                })
                .wiretap("tcpserver", LogLevel.INFO)
                .bindNow(Duration.ofSeconds(5));
    } else {
        throw new IllegalArgumentException("test implementation does not currently support the protocol " + protocol);
    }
}
 
Example #9
Source File: TcpServerTransport.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
private TcpServerTransport(TcpServer server) {
  this.server = server;
}
 
Example #10
Source File: RSocketListenerImpl.java    From alibaba-rsocket-broker with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {
    if (status != 1) {
        for (Map.Entry<Integer, String> entry : schemas.entrySet()) {
            String schema = entry.getValue();
            int port = entry.getKey();
            ServerTransport<?> transport;
            if (schema.equals("local")) {
                transport = LocalServerTransport.create("unittest");
            } else if (schema.equals("tcp")) {
                transport = TcpServerTransport.create(host, port);
            } else if (schema.equals("tcps")) {
                TcpServer tcpServer = TcpServer.create()
                        .host(host)
                        .port(port)
                        .secure(ssl -> ssl.sslContext(
                                SslContextBuilder.forServer(privateKey, (X509Certificate) certificate)
                                        .protocols(protocols)
                                        .sslProvider(getSslProvider())
                        ));
                transport = TcpServerTransport.create(tcpServer);
            } else if (schema.equals("ws")) {
                transport = WebsocketServerTransport.create(host, port);
            } else if (schema.equals("wss")) {
                HttpServer httpServer = HttpServer.create()
                        .host(host)
                        .port(port)
                        .secure(ssl -> ssl.sslContext(
                                SslContextBuilder.forServer(privateKey, (X509Certificate) certificate)
                                        .protocols(protocols)
                                        .sslProvider(getSslProvider())
                        ));
                transport = WebsocketServerTransport.create(httpServer);
            } else {
                transport = TcpServerTransport.create(host, port);
            }
            RSocketServer rsocketServer = RSocketServer.create();
            //acceptor interceptor
            for (SocketAcceptorInterceptor acceptorInterceptor : acceptorInterceptors) {
                rsocketServer.interceptors(interceptorRegistry -> {
                    interceptorRegistry.forSocketAcceptor(acceptorInterceptor);
                });
            }
            //connection interceptor
            for (DuplexConnectionInterceptor connectionInterceptor : connectionInterceptors) {
                rsocketServer.interceptors(interceptorRegistry -> {
                    interceptorRegistry.forConnection(connectionInterceptor);
                });

            }
            //responder interceptor
            for (RSocketInterceptor responderInterceptor : responderInterceptors) {
                rsocketServer.interceptors(interceptorRegistry -> {
                    interceptorRegistry.forResponder(responderInterceptor);
                });

            }
            Disposable disposable = rsocketServer
                    .acceptor(acceptor)
                    .bind(transport)
                    .onTerminateDetach()
                    .subscribe();
            responders.add(disposable);
            log.info(RsocketErrorCode.message("RST-100001", schema + "://" + host + ":" + port));
        }
        status = 1;
    }
}
 
Example #11
Source File: TcpServerTransportTest.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@DisplayName("creates client with TcpServer")
@Test
void createTcpClient() {
  assertThat(TcpServerTransport.create(TcpServer.create())).isNotNull();
}
 
Example #12
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void abort() {
	disposableServer =
			TcpServer.create()
			         .port(0)
			         .handle((in, out) ->
			                 in.receive()
			                   .take(1)
			                   .thenMany(Flux.defer(() ->
			                           out.withConnection(c ->
			                                   c.addHandlerFirst(new HttpResponseEncoder()))
			                              .sendObject(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
			                                                                      HttpResponseStatus.ACCEPTED))
			                              .then(Mono.delay(Duration.ofSeconds(2)).then()))))
			         .wiretap(true)
			         .bindNow();

	ConnectionProvider pool = ConnectionProvider.create("abort", 1);

	HttpClient client = createHttpClientForContextWithPort(pool);

	client.get()
	      .uri("/")
	      .responseSingle((r, buf) -> Mono.just(r.status().code()))
	      .log()
	      .block(Duration.ofSeconds(30));

	client.get()
	      .uri("/")
	      .responseContent()
	      .log()
	      .blockLast(Duration.ofSeconds(30));

	client.get()
	      .uri("/")
	      .responseContent()
	      .log()
	      .blockLast(Duration.ofSeconds(30));

	pool.dispose();
}
 
Example #13
Source File: DefaultPooledConnectionProviderTest.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void testIssue951_MaxPendingAcquire() throws InterruptedException {
	DisposableServer server =
			TcpServer.create()
			         .port(0)
			         .handle((in, out) -> out.sendString(Mono.just("test")
			                                                 .delayElement(Duration.ofMillis(100))))
			         .wiretap(true)
			         .bindNow();
	DefaultPooledConnectionProvider provider =
			(DefaultPooledConnectionProvider) ConnectionProvider.builder("testIssue951_MaxPendingAcquire")
			                                             .maxConnections(1)
			                                             .pendingAcquireTimeout(Duration.ofMillis(20))
			                                             .pendingAcquireMaxCount(1)
			                                             .build();
	CountDownLatch latch = new CountDownLatch(2);

	try {
		AtomicReference<InstrumentedPool<PooledConnection>> pool = new AtomicReference<>();
		List<? extends Signal<? extends Connection>> list =
				Flux.range(0, 3)
				    .flatMapDelayError(i ->
				        TcpClient.create(provider)
				                 .port(server.port())
				                 .doOnConnected(conn -> {
				                     ConcurrentMap<PooledConnectionProvider.PoolKey, InstrumentedPool<PooledConnection>> pools =
				                         provider.channelPools;
				                     pool.set(pools.get(pools.keySet().toArray()[0]));
				                 })
				                 .doOnDisconnected(conn -> latch.countDown())
				                 .handle((in, out) -> in.receive().then())
				                 .wiretap(true)
				                 .connect()
				                 .materialize(),
				    256, 32)
				    .collectList()
				    .doFinally(fin -> latch.countDown())
				    .block(Duration.ofSeconds(30));

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

		assertThat(list).isNotNull()
				.hasSize(3);

		int onNext = 0;
		int onErrorTimeout = 0;
		int onErrorPendingAcquire = 0;
		String msg1 = "Pool#acquire(Duration) has been pending for more than the configured timeout of 20ms";
		String msg2 = "Pending acquire queue has reached its maximum size of 1";
		for (int i = 0; i < 3; i++) {
			Signal<? extends Connection> signal = list.get(i);
			if (signal.isOnNext()) {
				onNext++;
			}
			else if (signal.getThrowable() instanceof TimeoutException &&
							 msg1.equals(signal.getThrowable().getMessage())) {
				onErrorTimeout++;
			}
			else if (signal.getThrowable() instanceof PoolAcquirePendingLimitException &&
							 msg2.equals(signal.getThrowable().getMessage())) {
				onErrorPendingAcquire++;
			}
		}
		assertThat(onNext).isEqualTo(1);
		assertThat(onErrorTimeout).isEqualTo(1);
		assertThat(onErrorPendingAcquire).isEqualTo(1);

		assertThat(pool.get().metrics().acquiredSize()).as("currently acquired").isEqualTo(0);
		assertThat(pool.get().metrics().idleSize()).as("currently idle").isEqualTo(0);
	}
	finally {
		server.disposeNow();
		provider.dispose();
	}
}
 
Example #14
Source File: DefaultPooledConnectionProviderTest.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void testIssue673_TimeoutException() throws InterruptedException {
	DisposableServer server =
			TcpServer.create()
			         .port(0)
			         .handle((in, out) -> out.sendString(Mono.just("test")
			                                                 .delayElement(Duration.ofMillis(100))))
			         .wiretap(true)
			         .bindNow();
	DefaultPooledConnectionProvider provider =
			(DefaultPooledConnectionProvider) ConnectionProvider.builder("testIssue673_TimeoutException")
			                                             .maxConnections(1)
			                                             .pendingAcquireMaxCount(4)
			                                             .pendingAcquireTimeout(Duration.ofMillis(10))
			                                             .build();
	CountDownLatch latch = new CountDownLatch(2);

	try {
		AtomicReference<InstrumentedPool<PooledConnection>> pool = new AtomicReference<>();
		List<? extends Signal<? extends Connection>> list =
				Flux.range(0, 5)
				    .flatMapDelayError(i ->
				        TcpClient.create(provider)
				                 .port(server.port())
				                 .doOnConnected(conn -> {
				                     ConcurrentMap<PooledConnectionProvider.PoolKey, InstrumentedPool<PooledConnection>> pools =
				                         provider.channelPools;
				                     pool.set(pools.get(pools.keySet().toArray()[0]));
				                 })
				                 .doOnDisconnected(conn -> latch.countDown())
				                 .handle((in, out) -> in.receive().then())
				                 .wiretap(true)
				                 .connect()
				                 .materialize(),
				    256, 32)
				    .collectList()
				    .doFinally(fin -> latch.countDown())
				    .block(Duration.ofSeconds(30));

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

		assertThat(list).isNotNull()
				.hasSize(5);

		int onNext = 0;
		int onError = 0;
		String msg = "Pool#acquire(Duration) has been pending for more than the configured timeout of 10ms";
		for (int i = 0; i < 5; i++) {
			Signal<? extends Connection> signal = list.get(i);
			if (signal.isOnNext()) {
				onNext++;
			}
			else if (signal.getThrowable() instanceof TimeoutException &&
							 msg.equals(signal.getThrowable().getMessage())) {
				onError++;
			}
		}
		assertThat(onNext).isEqualTo(1);
		assertThat(onError).isEqualTo(4);

		assertThat(pool.get().metrics().acquiredSize()).as("currently acquired").isEqualTo(0);
		assertThat(pool.get().metrics().idleSize()).as("currently idle").isEqualTo(0);
	}
	finally {
		server.disposeNow();
		provider.dispose();
	}
}
 
Example #15
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
protected TcpServer duplicate() {
	throw new UnsupportedOperationException();
}
 
Example #16
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer wiretap(String category, LogLevel level) {
	httpServer = httpServer.wiretap(category, level);
	return this;
}
 
Example #17
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer wiretap(String category) {
	httpServer = httpServer.wiretap(category);
	return this;
}
 
Example #18
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer wiretap(boolean enable) {
	httpServer = httpServer.wiretap(enable);
	return this;
}
 
Example #19
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer secure(SslProvider sslProvider) {
	httpServer = httpServer.secure(sslProvider);
	return this;
}
 
Example #20
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer secure(Consumer<? super SslProvider.SslContextSpec> sslProviderBuilder) {
	httpServer = httpServer.secure(sslProviderBuilder);
	return this;
}
 
Example #21
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer runOn(LoopResources channelResources) {
	httpServer = httpServer.runOn(channelResources);
	return this;
}
 
Example #22
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public <A> TcpServer attr(AttributeKey<A> key, @Nullable A value) {
	httpServer = httpServer.attr(key, value);
	return this;
}
 
Example #23
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer bindAddress(Supplier<? extends SocketAddress> bindAddressSupplier) {
	httpServer = httpServer.bindAddress(bindAddressSupplier);
	return this;
}
 
Example #24
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public <A> TcpServer childAttr(AttributeKey<A> key, @Nullable A value) {
	httpServer = httpServer.childAttr(key, value);
	return this;
}
 
Example #25
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer childObserve(ConnectionObserver observer) {
	httpServer = httpServer.childObserve(observer);
	return this;
}
 
Example #26
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public <A> TcpServer childOption(ChannelOption<A> key, @Nullable A value) {
	httpServer = httpServer.childOption(key, value);
	return this;
}
 
Example #27
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer handle(BiFunction<? super NettyInbound, ? super NettyOutbound, ? extends Publisher<Void>> handler) {
	httpServer = httpServer.handle(handler);
	return this;
}
 
Example #28
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer metrics(boolean enable) {
	httpServer = httpServer.metrics(enable, Function.identity());
	return this;
}
 
Example #29
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer metrics(boolean enable, Supplier<? extends ChannelMetricsRecorder> recorder) {
	httpServer = httpServer.metrics(enable, recorder);
	return this;
}
 
Example #30
Source File: HttpServerTcpConfig.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Override
public TcpServer observe(ConnectionObserver observer) {
	httpServer = httpServer.observe(observer);
	return this;
}