io.rsocket.transport.netty.client.TcpClientTransport Java Examples

The following examples show how to use io.rsocket.transport.netty.client.TcpClientTransport. 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: RSocketServerToClientIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private static void connectAndVerify(String destination) {

		ServerController serverController = context.getBean(ServerController.class);
		serverController.reset();

		RSocket rsocket = null;
		try {
			rsocket = RSocketFactory.connect()
					.setupPayload(DefaultPayload.create("", destination))
					.dataMimeType("text/plain")
					.frameDecoder(PayloadDecoder.ZERO_COPY)
					.acceptor(context.getBean("clientAcceptor", MessageHandlerAcceptor.class))
					.transport(TcpClientTransport.create("localhost", 7000))
					.start()
					.block();

			serverController.await(Duration.ofSeconds(5));
		}
		finally {
			if (rsocket != null) {
				rsocket.dispose();
			}
		}
	}
 
Example #2
Source File: TcpSslUriHandler.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<ClientTransport> buildClient(URI uri) {
    Objects.requireNonNull(uri, "uri must not be null");

    if (!SCHEME.equals(uri.getScheme())) {
        return Optional.empty();
    }
    try {
        SslContext context = SslContextBuilder
                .forClient()
                .protocols(protocols)
                .sslProvider(getSslProvider())
                .trustManager(trustManagerFactory).build();
        TcpClient tcpClient = TcpClient.create()
                .host(uri.getHost())
                .port(uri.getPort())
                .secure(ssl -> ssl.sslContext(context));
        return Optional.of(TcpClientTransport.create(tcpClient));
    } catch (Exception e) {
        return Optional.empty();
    }
}
 
Example #3
Source File: PingPongApp.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
	ConfigurableEnvironment env = event.getApplicationContext().getEnvironment();
	Integer pongDelay = env.getProperty("pong.delay", Integer.class, 5000);
	try {
		Thread.sleep(pongDelay);
	}
	catch (InterruptedException e) {
		e.printStackTrace();
	}
	log.info("Starting Pong");
	Integer gatewayPort = env.getProperty("spring.rsocket.server.port",
			Integer.class, 7002);
	MicrometerRSocketInterceptor interceptor = new MicrometerRSocketInterceptor(
			meterRegistry, Tag.of("component", "pong"));

	ByteBuf announcementMetadata = getRouteSetupMetadata(strategies, "pong", 3L);
	RSocketFactory.connect().metadataMimeType(COMPOSITE_MIME_TYPE.toString())
			.setupPayload(
					DefaultPayload.create(EMPTY_BUFFER, announcementMetadata))
			.addRequesterPlugin(interceptor).acceptor(this::accept)
			.transport(TcpClientTransport.create(gatewayPort)) // proxy
			.start().block();
}
 
Example #4
Source File: ClientStreamingToServer.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  RSocketServer.create(
          SocketAcceptor.forRequestStream(
              payload ->
                  Flux.interval(Duration.ofMillis(100))
                      .map(aLong -> DefaultPayload.create("Interval: " + aLong))))
      .bind(TcpServerTransport.create("localhost", 7000))
      .subscribe();

  RSocket socket =
      RSocketConnector.connectWith(TcpClientTransport.create("localhost", 7000)).block();

  socket
      .requestStream(DefaultPayload.create("Hello"))
      .map(Payload::getDataUtf8)
      .doOnNext(logger::debug)
      .take(10)
      .then()
      .doFinally(signalType -> socket.dispose())
      .then()
      .block();
}
 
Example #5
Source File: MarketDataRSocketControllerLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
@Lazy
public RSocket rSocket() {
    return RSocketFactory.connect()
                         .mimeType(MimeTypeUtils.APPLICATION_JSON_VALUE, MimeTypeUtils.APPLICATION_JSON_VALUE)
                         .frameDecoder(PayloadDecoder.ZERO_COPY)
                         .transport(TcpClientTransport.create(7000))
                         .start()
                         .block();
}
 
Example #6
Source File: ClientConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
@Bean
public RSocket rSocket() {
    return RSocketFactory.connect()
                         .mimeType(MimeTypeUtils.APPLICATION_JSON_VALUE, MimeTypeUtils.APPLICATION_JSON_VALUE)
                         .frameDecoder(PayloadDecoder.ZERO_COPY)
                         .transport(TcpClientTransport.create(7000))
                         .start()
                         .block();
}
 
Example #7
Source File: FireNForgetClient.java    From tutorials with MIT License 5 votes vote down vote up
public FireNForgetClient() {
    this.socket = RSocketFactory.connect()
      .transport(TcpClientTransport.create("localhost", TCP_PORT))
      .start()
      .block();
    this.data = Collections.unmodifiableList(generateData());
}
 
Example #8
Source File: ChannelClient.java    From tutorials with MIT License 5 votes vote down vote up
public ChannelClient() {
    this.socket = RSocketFactory.connect()
      .transport(TcpClientTransport.create("localhost", TCP_PORT))
      .start()
      .block();

    this.gameController = new GameController("Client Player");
}
 
Example #9
Source File: SetupRejectionTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
static Stream<Arguments> transports() {
  Function<InetSocketAddress, ServerTransport<CloseableChannel>> tcpServer =
      TcpServerTransport::create;
  Function<InetSocketAddress, ServerTransport<CloseableChannel>> wsServer =
      WebsocketServerTransport::create;
  Function<InetSocketAddress, ClientTransport> tcpClient = TcpClientTransport::create;
  Function<InetSocketAddress, ClientTransport> wsClient = WebsocketClientTransport::create;

  return Stream.of(Arguments.of(tcpServer, tcpClient), Arguments.of(wsServer, wsClient));
}
 
Example #10
Source File: TcpPing.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
private static PingClient newPingClient(boolean isResumable) {
  RSocketConnector connector = RSocketConnector.create();
  if (isResumable) {
    connector.resume(new Resume());
  }
  Mono<RSocket> rSocket =
      connector
          .payloadDecoder(PayloadDecoder.ZERO_COPY)
          .keepAlive(Duration.ofMinutes(1), Duration.ofMinutes(30))
          .connect(TcpClientTransport.create(port));

  return new PingClient(rSocket);
}
 
Example #11
Source File: RSocketFactoryNettyTransportFragmentationTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("arguments")
void clientSucceedsWithDisabledFragmentation(ServerTransport<CloseableChannel> serverTransport) {
  CloseableChannel server = RSocketServer.create(mockAcceptor()).bind(serverTransport).block();

  Mono<RSocket> rSocket =
      RSocketConnector.connectWith(TcpClientTransport.create(server.address()))
          .doFinally(s -> server.dispose());
  StepVerifier.create(rSocket).expectNextCount(1).expectComplete().verify(Duration.ofSeconds(5));
}
 
Example #12
Source File: RSocketFactoryNettyTransportFragmentationTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("arguments")
void clientSucceedsWithEnabledFragmentationOnSufficientMtu(
    ServerTransport<CloseableChannel> serverTransport) {
  CloseableChannel server =
      RSocketServer.create(mockAcceptor()).fragment(100).bind(serverTransport).block();

  Mono<RSocket> rSocket =
      RSocketConnector.create()
          .fragment(100)
          .connect(TcpClientTransport.create(server.address()))
          .doFinally(s -> server.dispose());
  StepVerifier.create(rSocket).expectNextCount(1).expectComplete().verify(Duration.ofSeconds(5));
}
 
Example #13
Source File: InteractionsLoadTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
@SlowTest
public void channel() {
  CloseableChannel server =
      RSocketServer.create(SocketAcceptor.with(new EchoRSocket()))
          .bind(TcpServerTransport.create("localhost", 0))
          .block(Duration.ofSeconds(10));

  RSocket clientRSocket =
      RSocketConnector.connectWith(TcpClientTransport.create(server.address()))
          .block(Duration.ofSeconds(10));

  int concurrency = 16;
  Flux.range(1, concurrency)
      .flatMap(
          v ->
              clientRSocket
                  .requestChannel(
                      input().onBackpressureDrop().map(iv -> DefaultPayload.create("foo")))
                  .limitRate(10000),
          concurrency)
      .timeout(Duration.ofSeconds(5))
      .doOnNext(
          p -> {
            String data = p.getDataUtf8();
            if (!data.equals("bar")) {
              throw new IllegalStateException("Channel Client Bad message: " + data);
            }
          })
      .window(Duration.ofSeconds(1))
      .flatMap(Flux::count)
      .doOnNext(d -> System.out.println("Got: " + d))
      .take(Duration.ofMinutes(1))
      .doOnTerminate(server::dispose)
      .subscribe();

  server.onClose().block();
}
 
Example #14
Source File: RSocketClientExample.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

    RSocketServer.create(
            SocketAcceptor.forRequestResponse(
                p -> {
                  String data = p.getDataUtf8();
                  logger.info("Received request data {}", data);

                  Payload responsePayload = DefaultPayload.create("Echo: " + data);
                  p.release();

                  return Mono.just(responsePayload);
                }))
        .bind(TcpServerTransport.create("localhost", 7000))
        .delaySubscription(Duration.ofSeconds(5))
        .doOnNext(cc -> logger.info("Server started on the address : {}", cc.address()))
        .subscribe();

    RSocketClient rSocketClient =
        RSocketConnector.create()
            .reconnect(Retry.backoff(50, Duration.ofMillis(500)))
            .toRSocketClient(TcpClientTransport.create("localhost", 7000));

    rSocketClient
        .requestResponse(Mono.just(DefaultPayload.create("Test Request")))
        .doOnSubscribe(s -> logger.info("Executing Request"))
        .doOnNext(
            d -> {
              logger.info("Received response data {}", d.getDataUtf8());
              d.release();
            })
        .repeat(10)
        .blockLast();
  }
 
Example #15
Source File: HelloWorldClient.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

    RSocket rsocket =
        new RSocket() {
          boolean fail = true;

          @Override
          public Mono<Payload> requestResponse(Payload p) {
            if (fail) {
              fail = false;
              return Mono.error(new Throwable("Simulated error"));
            } else {
              return Mono.just(p);
            }
          }
        };

    RSocketServer.create(SocketAcceptor.with(rsocket))
        .bind(TcpServerTransport.create("localhost", 7000))
        .subscribe();

    RSocket socket =
        RSocketConnector.connectWith(TcpClientTransport.create("localhost", 7000)).block();

    for (int i = 0; i < 3; i++) {
      socket
          .requestResponse(DefaultPayload.create("Hello"))
          .map(Payload::getDataUtf8)
          .onErrorReturn("error")
          .doOnNext(logger::debug)
          .block();
    }

    socket.dispose();
  }
 
Example #16
Source File: TcpUriHandler.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<ClientTransport> buildClient(URI uri) {
  Objects.requireNonNull(uri, "uri must not be null");

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

  return Optional.of(TcpClientTransport.create(uri.getHost(), uri.getPort()));
}
 
Example #17
Source File: PingPongApp.java    From spring-cloud-rsocket with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
	log.info("Starting Ping" + id);
	ConfigurableEnvironment env = event.getApplicationContext().getEnvironment();
	Integer take = env.getProperty("ping.take", Integer.class, null);
	Integer gatewayPort = env.getProperty("spring.rsocket.server.port",
			Integer.class, 7002);

	log.debug("ping.take: " + take);

	MicrometerRSocketInterceptor interceptor = new MicrometerRSocketInterceptor(
			meterRegistry, Tag.of("component", "ping"));
	ByteBuf metadata = getRouteSetupMetadata(strategies, "ping", id);
	Payload setupPayload = DefaultPayload.create(EMPTY_BUFFER, metadata);

	pongFlux = RSocketFactory.connect().frameDecoder(PayloadDecoder.ZERO_COPY)
			.metadataMimeType(COMPOSITE_MIME_TYPE.toString())
			.setupPayload(setupPayload).addRequesterPlugin(interceptor)
			.transport(TcpClientTransport.create(gatewayPort)) // proxy
			.start().log("startPing" + id)
			.flatMapMany(socket -> doPing(take, socket)).cast(String.class)
			.doOnSubscribe(o -> {
				if (log.isDebugEnabled()) {
					log.debug("ping doOnSubscribe");
				}
			});

	boolean subscribe = env.getProperty("ping.subscribe", Boolean.class, true);

	if (subscribe) {
		pongFlux.subscribe();
	}
}
 
Example #18
Source File: ChannelEchoClient.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

    SocketAcceptor echoAcceptor =
        SocketAcceptor.forRequestChannel(
            payloads ->
                Flux.from(payloads)
                    .map(Payload::getDataUtf8)
                    .map(s -> "Echo: " + s)
                    .map(DefaultPayload::create));

    RSocketServer.create(echoAcceptor)
        .bind(TcpServerTransport.create("localhost", 7000))
        .subscribe();

    RSocket socket =
        RSocketConnector.connectWith(TcpClientTransport.create("localhost", 7000)).block();

    socket
        .requestChannel(
            Flux.interval(Duration.ofMillis(1000)).map(i -> DefaultPayload.create("Hello")))
        .map(Payload::getDataUtf8)
        .doOnNext(logger::debug)
        .take(10)
        .doFinally(signalType -> socket.dispose())
        .then()
        .block();
  }
 
Example #19
Source File: RsocketClientApplication.java    From bootiful-reactive-microservices with Apache License 2.0 5 votes vote down vote up
@Bean
RSocket rSocket() {
	return RSocketFactory
		.connect()
		.frameDecoder(PayloadDecoder.ZERO_COPY)
		.dataMimeType(MimeTypeUtils.APPLICATION_JSON_VALUE)
		.transport(TcpClientTransport.create(7000))
		.start()
		.block();
}
 
Example #20
Source File: DefaultRSocketRequesterBuilder.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Mono<RSocketRequester> connectTcp(String host, int port) {
	return connect(TcpClientTransport.create(host, port));
}
 
Example #21
Source File: TaskProcessingWithServerSideNotificationsExample.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
  UnicastProcessor<Task> tasksProcessor =
      UnicastProcessor.create(Queues.<Task>unboundedMultiproducer().get());
  ConcurrentMap<String, BlockingQueue<Task>> idToCompletedTasksMap = new ConcurrentHashMap<>();
  ConcurrentMap<String, RSocket> idToRSocketMap = new ConcurrentHashMap<>();
  BackgroundWorker backgroundWorker =
      new BackgroundWorker(tasksProcessor, idToCompletedTasksMap, idToRSocketMap);

  RSocketServer.create(new TasksAcceptor(tasksProcessor, idToCompletedTasksMap, idToRSocketMap))
      .bindNow(TcpServerTransport.create(9991));

  Logger logger = LoggerFactory.getLogger("RSocket.Client.ID[Test]");

  Mono<RSocket> rSocketMono =
      RSocketConnector.create()
          .setupPayload(DefaultPayload.create("Test"))
          .acceptor(
              SocketAcceptor.forFireAndForget(
                  p -> {
                    logger.info("Received Processed Task[{}]", p.getDataUtf8());
                    p.release();
                    return Mono.empty();
                  }))
          .connect(TcpClientTransport.create(9991));

  RSocket rSocketRequester1 = rSocketMono.block();

  for (int i = 0; i < 10; i++) {
    rSocketRequester1.fireAndForget(DefaultPayload.create("task" + i)).block();
  }

  Thread.sleep(4000);

  rSocketRequester1.dispose();
  logger.info("Disposed");

  Thread.sleep(4000);

  RSocket rSocketRequester2 = rSocketMono.block();

  logger.info("Reconnected");

  Thread.sleep(10000);
}
 
Example #22
Source File: ArgsTest.java    From rsc with Apache License 2.0 4 votes vote down vote up
@Test
void clientTransportTcp() {
	final Args args = new Args(new String[]{"tcp://localhost:8080"});
	final ClientTransport clientTransport = args.clientTransport();
	assertThat(clientTransport).isOfAnyClassIn(TcpClientTransport.class);
}
 
Example #23
Source File: ReqResClient.java    From tutorials with MIT License 4 votes vote down vote up
public ReqResClient() {
    this.socket = RSocketFactory.connect()
      .transport(TcpClientTransport.create("localhost", TCP_PORT))
      .start()
      .block();
}
 
Example #24
Source File: ReqStreamClient.java    From tutorials with MIT License 4 votes vote down vote up
public ReqStreamClient() {
    this.socket = RSocketFactory.connect()
      .transport(TcpClientTransport.create("localhost", TCP_PORT))
      .start()
      .block();
}
 
Example #25
Source File: ClientRSocketRequesterBuilder.java    From spring-cloud-rsocket with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<RSocketRequester> connectTcp(String host, int port) {
	return connect(TcpClientTransport.create(host, port));
}
 
Example #26
Source File: UserServiceRsocketClientImpl.java    From rpc-benchmark with Apache License 2.0 4 votes vote down vote up
public UserServiceRsocketClientImpl() {
    this.rSocket =
            RSocketFactory.connect().transport(TcpClientTransport.create(8080)).start().block();
    this.userServiceClient = new UserServiceClient(rSocket);
}
 
Example #27
Source File: FragmentTest.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
private RSocket buildClient(int frameSize) {
  return RSocketConnector.create()
      .fragment(frameSize)
      .connect(TcpClientTransport.create(server.address()))
      .block();
}
 
Example #28
Source File: ResumeIntegrationTest.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
static ClientTransport clientTransport(InetSocketAddress address) {
  return TcpClientTransport.create(address);
}
 
Example #29
Source File: TcpIntegrationTest.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
private RSocket buildClient() {
  return RSocketConnector.connectWith(TcpClientTransport.create(server.address())).block();
}
 
Example #30
Source File: ResumeFileTransfer.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

    Resume resume =
        new Resume()
            .sessionDuration(Duration.ofMinutes(5))
            .retry(
                Retry.fixedDelay(Long.MAX_VALUE, Duration.ofSeconds(1))
                    .doBeforeRetry(s -> logger.debug("Disconnected. Trying to resume...")));

    RequestCodec codec = new RequestCodec();

    CloseableChannel server =
        RSocketServer.create(
                SocketAcceptor.forRequestStream(
                    payload -> {
                      Request request = codec.decode(payload);
                      payload.release();
                      String fileName = request.getFileName();
                      int chunkSize = request.getChunkSize();

                      Flux<Long> ticks = Flux.interval(Duration.ofMillis(500)).onBackpressureDrop();

                      return Files.fileSource(fileName, chunkSize)
                          .map(DefaultPayload::create)
                          .zipWith(ticks, (p, tick) -> p);
                    }))
            .resume(resume)
            .bind(TcpServerTransport.create("localhost", 8000))
            .block();

    RSocket client =
        RSocketConnector.create()
            .resume(resume)
            .connect(TcpClientTransport.create("localhost", 8001))
            .block();

    client
        .requestStream(codec.encode(new Request(16, "lorem.txt")))
        .doFinally(s -> server.dispose())
        .subscribe(Files.fileSink("rsocket-examples/out/lorem_output.txt", PREFETCH_WINDOW_SIZE));

    server.onClose().block();
  }