io.rsocket.transport.netty.server.TcpServerTransport Java Examples

The following examples show how to use io.rsocket.transport.netty.server.TcpServerTransport. 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: RSocketBufferLeakTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@BeforeClass
@SuppressWarnings("ConstantConditions")
public static void setupOnce() {
	context = new AnnotationConfigApplicationContext(ServerConfig.class);

	server = RSocketFactory.receive()
			.frameDecoder(PayloadDecoder.ZERO_COPY)
			.addServerPlugin(payloadInterceptor) // intercept responding
			.acceptor(context.getBean(MessageHandlerAcceptor.class))
			.transport(TcpServerTransport.create("localhost", 7000))
			.start()
			.block();

	requester = RSocketRequester.builder()
			.rsocketFactory(factory -> {
				factory.frameDecoder(PayloadDecoder.ZERO_COPY);
				factory.addClientPlugin(payloadInterceptor); // intercept outgoing requests
			})
			.rsocketStrategies(context.getBean(RSocketStrategies.class))
			.connectTcp("localhost", 7000)
			.block();
}
 
Example #2
Source File: RSocketClientToServerIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@BeforeClass
@SuppressWarnings("ConstantConditions")
public static void setupOnce() {
	context = new AnnotationConfigApplicationContext(ServerConfig.class);

	server = RSocketFactory.receive()
			.addServerPlugin(interceptor)
			.frameDecoder(PayloadDecoder.ZERO_COPY)
			.acceptor(context.getBean(MessageHandlerAcceptor.class))
			.transport(TcpServerTransport.create("localhost", 7000))
			.start()
			.block();

	requester = RSocketRequester.builder()
			.rsocketFactory(factory -> factory.frameDecoder(PayloadDecoder.ZERO_COPY))
			.rsocketStrategies(context.getBean(RSocketStrategies.class))
			.connectTcp("localhost", 7000)
			.block();
}
 
Example #3
Source File: TcpPongServer.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) {
  System.out.println("Starting TCP ping-pong server");
  System.out.println("port: " + port);
  System.out.println("resume enabled: " + isResume);

  RSocketServer server = RSocketServer.create(new PingHandler());
  if (isResume) {
    server.resume(new Resume());
  }
  server
      .payloadDecoder(PayloadDecoder.ZERO_COPY)
      .bind(TcpServerTransport.create("localhost", port))
      .block()
      .onClose()
      .block();
}
 
Example #4
Source File: RSocketRpcServer.java    From rpc-thunderdome with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) {
  String host = System.getProperty("host", "127.0.0.1");
  int port = Integer.getInteger("port", 8001);
  RSocketFactory.receive()
      .frameDecoder(Frame::retain)
      .acceptor(
          (setup, sendingSocket) ->
              Mono.just(
                  new SimpleServiceServer(
                      new DefaultService(), Optional.empty(), Optional.empty())))
      .transport(TcpServerTransport.create(host, port))
      .start()
      .block()
      .onClose()
      .doOnSubscribe(s -> logger.info("server started"))
      .block();
}
 
Example #5
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 #6
Source File: RSocketServerToClientIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@BeforeClass
@SuppressWarnings("ConstantConditions")
public static void setupOnce() {
	context = new AnnotationConfigApplicationContext(RSocketConfig.class);

	server = RSocketFactory.receive()
			.frameDecoder(PayloadDecoder.ZERO_COPY)
			.acceptor(context.getBean("serverAcceptor", MessageHandlerAcceptor.class))
			.transport(TcpServerTransport.create("localhost", 7000))
			.start()
			.block();
}
 
Example #7
Source File: Server.java    From tutorials with MIT License 5 votes vote down vote up
public Server() {
    this.server = RSocketFactory.receive()
      .acceptor((setupPayload, reactiveSocket) -> Mono.just(new RSocketImpl()))
      .transport(TcpServerTransport.create("localhost", TCP_PORT))
      .start()
      .doOnNext(x -> LOG.info("Server started"))
      .subscribe();

    this.gameController = new GameController("Server Player");
}
 
Example #8
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 #9
Source File: TcpClientTransportTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("connects to server")
@Test
void connect() {
  InetSocketAddress address = InetSocketAddress.createUnresolved("localhost", 0);

  TcpServerTransport serverTransport = TcpServerTransport.create(address);

  serverTransport
      .start(duplexConnection -> Mono.empty())
      .flatMap(context -> TcpClientTransport.create(context.address()).connect())
      .as(StepVerifier::create)
      .expectNextCount(1)
      .verifyComplete();
}
 
Example #10
Source File: TcpIntegrationTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Before
public void startup() {
  server =
      RSocketServer.create((setup, sendingSocket) -> Mono.just(new RSocketProxy(handler)))
          .bind(TcpServerTransport.create("localhost", 0))
          .block();
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: Server.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args){
    UserServiceServer userServiceServer = new UserServiceServer(new UserServiceRsocketServerImpl(), Optional.empty(), Optional.empty());
    CloseableChannel closeableChannel =
            RSocketFactory.receive()
                    .acceptor(
                            (setup, sendingSocket) -> Mono.just(new RequestHandlingRSocket(userServiceServer)))
                    .transport(TcpServerTransport.create(8080))
                    .start()
                    .block();

    // Block so we don't exit
    closeableChannel.onClose().block();
}
 
Example #16
Source File: ReservationServiceApplication.java    From bootiful-reactive-microservices with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {

	SocketAcceptor sa =
		(connectionSetupPayload, rSocket) -> Mono.just(new AbstractRSocket() {
			@Override
			public Flux<Payload> requestStream(Payload payload) {
				return
					reservationRepository
						.findAll()
						.map(x -> {
							try {
								return mapper.writeValueAsString(x);
							}
							catch (JsonProcessingException e) {
								throw new RuntimeException(e);
							}
						})
						.map(DefaultPayload::create);
			}
		});

	RSocketFactory
		.receive()
		.acceptor(sa)
		.transport(TcpServerTransport.create("localhost", 7000))
		.start()
		.onTerminateDetach()
		.subscribe();
}
 
Example #17
Source File: RSocketConfiguration.java    From liiklus with MIT License 5 votes vote down vote up
@Override
public void initialize(GenericApplicationContext applicationContext) {
    var environment = applicationContext.getEnvironment();

    if (!environment.acceptsProfiles(Profiles.of("gateway"))) {
        return;
    }

    var serverProperties = PropertiesUtil.bind(environment, new RSocketServerProperties());

    if (!serverProperties.isEnabled()) {
        return;
    }

    applicationContext.registerBean(RSocketLiiklusService.class);

    applicationContext.registerBean(
            CloseableChannel.class,
            () -> {
                var liiklusService = applicationContext.getBean(LiiklusService.class);

                return RSocketFactory.receive()
                        .acceptor((setup, sendingSocket) -> Mono.just(new RequestHandlingRSocket(new LiiklusServiceServer(liiklusService, Optional.empty(), Optional.empty()))))
                        .transport(TcpServerTransport.create(serverProperties.getHost(), serverProperties.getPort()))
                        .start()
                        .block();
            },
            it -> {
                it.setDestroyMethodName("dispose");
            }
    );
}
 
Example #18
Source File: RSocketService.java    From staccato with Apache License 2.0 5 votes vote down vote up
public RSocketService(RSocketConfigProps configProps, ItemSocketAcceptor itemSocketAcceptor) {
    log.info("Starting RSocket");
    TcpServerTransport tcp = TcpServerTransport.create("0.0.0.0", configProps.getPort());
    RSocketFactory.receive()
            .acceptor(itemSocketAcceptor)
            .transport(tcp)
            .start().log()
            .subscribe(channel -> log.info("RSocket initialized on port " + configProps.getPort()));
}
 
Example #19
Source File: RSocketServerToClientITest.java    From spring-rsocket-demo with GNU General Public License v3.0 5 votes vote down vote up
@BeforeAll
public static void setupOnce() {
    // create a client identity spring for this test suite
    clientId = UUID.randomUUID().toString();

    // create a Spring context for this test suite and obtain some beans
    context = new AnnotationConfigApplicationContext(ServerConfig.class);

    // Create an RSocket server for use in testing
    RSocketMessageHandler messageHandler = context.getBean(RSocketMessageHandler.class);
    server = RSocketServer.create(messageHandler.responder())
            .payloadDecoder(PayloadDecoder.ZERO_COPY)
            .bind(TcpServerTransport.create("localhost", 0))
            .block();
}
 
Example #20
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 #21
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();
  }
 
Example #22
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 #23
Source File: ReactiveSocketsAutoConfiguration.java    From spring-cloud-sockets with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean(ServerTransport.class)
public ServerTransport transport(){
	logger.info("Creating transport : {} on [ {}:{} ]", TcpServerTransport.class.getName(), properties.getHost(), properties.getPort());
	return TcpServerTransport.create(properties.getHost(), properties.getPort());
}
 
Example #24
Source File: LimitRateInterceptorExample.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  RSocketServer.create(
          SocketAcceptor.with(
              new RSocket() {
                @Override
                public Flux<Payload> requestStream(Payload payload) {
                  return Flux.interval(Duration.ofMillis(100))
                      .doOnRequest(
                          e -> logger.debug("Server publisher receives request for " + e))
                      .map(aLong -> DefaultPayload.create("Interval: " + aLong));
                }

                @Override
                public Flux<Payload> requestChannel(Publisher<Payload> payloads) {
                  return Flux.from(payloads)
                      .doOnRequest(
                          e -> logger.debug("Server publisher receives request for " + e));
                }
              }))
      .interceptors(registry -> registry.forResponder(LimitRateInterceptor.forResponder(64)))
      .bind(TcpServerTransport.create("localhost", 7000))
      .subscribe();

  RSocket socket =
      RSocketConnector.create()
          .interceptors(registry -> registry.forRequester(LimitRateInterceptor.forRequester(64)))
          .connect(TcpClientTransport.create("localhost", 7000))
          .block();

  logger.debug(
      "\n\nStart of requestStream interaction\n" + "----------------------------------\n");

  socket
      .requestStream(DefaultPayload.create("Hello"))
      .doOnRequest(e -> logger.debug("Client sends requestN(" + e + ")"))
      .map(Payload::getDataUtf8)
      .doOnNext(logger::debug)
      .take(10)
      .then()
      .block();

  logger.debug(
      "\n\nStart of requestChannel interaction\n" + "-----------------------------------\n");

  socket
      .requestChannel(
          Flux.<Payload, Long>generate(
                  () -> 1L,
                  (s, sink) -> {
                    sink.next(DefaultPayload.create("Next " + s));
                    return ++s;
                  })
              .doOnRequest(e -> logger.debug("Client publisher receives request for " + e)))
      .doOnRequest(e -> logger.debug("Client sends requestN(" + e + ")"))
      .map(Payload::getDataUtf8)
      .doOnNext(logger::debug)
      .take(10)
      .then()
      .doFinally(signalType -> socket.dispose())
      .then()
      .block();
}
 
Example #25
Source File: LeaseExample.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  // Queue for incoming messages represented as Flux
  // Imagine that every fireAndForget that is pushed is processed by a worker

  int queueCapacity = 50;
  BlockingQueue<String> messagesQueue = new ArrayBlockingQueue<>(queueCapacity);

  // emulating a worker that process data from the queue
  Thread workerThread =
      new Thread(
          () -> {
            try {
              while (!Thread.currentThread().isInterrupted()) {
                String message = messagesQueue.take();
                logger.info("Process message {}", message);
                Thread.sleep(500); // emulating processing
              }
            } catch (InterruptedException e) {
              throw new RuntimeException(e);
            }
          });

  workerThread.start();

  CloseableChannel server =
      RSocketServer.create(
              (setup, sendingSocket) ->
                  Mono.just(
                      new RSocket() {
                        @Override
                        public Mono<Void> fireAndForget(Payload payload) {
                          // add element. if overflows errors and terminates execution
                          // specifically to show that lease can limit rate of fnf requests in
                          // that example
                          try {
                            if (!messagesQueue.offer(payload.getDataUtf8())) {
                              logger.error("Queue has been overflowed. Terminating execution");
                              sendingSocket.dispose();
                              workerThread.interrupt();
                            }
                          } finally {
                            payload.release();
                          }
                          return Mono.empty();
                        }
                      }))
          .lease(() -> Leases.create().sender(new LeaseCalculator(SERVER_TAG, messagesQueue)))
          .bindNow(TcpServerTransport.create("localhost", 7000));

  LeaseReceiver receiver = new LeaseReceiver(CLIENT_TAG);
  RSocket clientRSocket =
      RSocketConnector.create()
          .lease(() -> Leases.create().receiver(receiver))
          .connect(TcpClientTransport.create(server.address()))
          .block();

  Objects.requireNonNull(clientRSocket);

  // generate stream of fnfs
  Flux.generate(
          () -> 0L,
          (state, sink) -> {
            sink.next(state);
            return state + 1;
          })
      // here we wait for the first lease for the responder side and start execution
      // on if there is allowance
      .delaySubscription(receiver.notifyWhenNewLease().then())
      .concatMap(
          tick -> {
            logger.info("Requesting FireAndForget({})", tick);
            return Mono.defer(() -> clientRSocket.fireAndForget(ByteBufPayload.create("" + tick)))
                .retryWhen(
                    Retry.indefinitely()
                        // ensures that error is the result of missed lease
                        .filter(t -> t instanceof MissingLeaseException)
                        .doBeforeRetryAsync(
                            rs -> {
                              // here we create a mechanism to delay the retry until
                              // the new lease allowance comes in.
                              logger.info("Ran out of leases {}", rs);
                              return receiver.notifyWhenNewLease().then();
                            }));
          })
      .blockLast();

  clientRSocket.onClose().block();
  server.dispose();
}
 
Example #26
Source File: ResumeIntegrationTest.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
static ServerTransport<CloseableChannel> serverTransport(String host, int port) {
  return TcpServerTransport.create(host, port);
}
 
Example #27
Source File: RSocketFactoryNettyTransportFragmentationTest.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
static Stream<? extends ServerTransport<CloseableChannel>> arguments() {
  return Stream.of(TcpServerTransport.create(0), WebsocketServerTransport.create(0));
}
 
Example #28
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;
    }
}