Search code examples
javaspring-bootspring-webfluxrsocket

How does Spring Boot RSocket detect disconnection?


everyone.
I want to make chatting server using RSocket.
The code below stores user information when the user accesses it.

  private final List<RSocketRequester> CLIENTS = new ArrayList<>();

  @ConnectMapping
  public void onConnect(RSocketRequester reqer) {
    log.info("RSocket Connect Mapping Start : reqer {}", reqer.hashCode());

    reqer.rsocket()
        .onClose()
        .doFirst(() -> CLIENTS.add(reqer))
        .doOnError(error -> log.info("RSocket Connect Error : error {}", error))
        .doFinally(consumer -> {
          CLIENTS.remove(reqer);
        })
        .subscribe();

    log.info("RSocket Connect Mapping End : Clients {}", this.CLIENTS.size());
  }
spring:
  rsocket:
    server:
      port: 6565
      transport: websocket
      mapping-path: /rs

I want to get user information when the user disconnects.
Can the RSocket detect when the user disconnects?
help me please.


Solution

  • If you configured rsocket security you can access AuthenticationPrincipal at onConnect().

    Simple example

    @ConnectMapping
    public void onConnect(RSocketRequester requester, @AuthenticationPrincipal Jwt principal) {
        requester.rsocket()
                .onClose()
                .doFirst(() -> {
                    System.out.println(principal.getSubject());
                    System.out.println("-----------------CONNNEEEECTED-----------------");
                })
                .doOnError(error -> {
                })
                .doFinally(consumer -> {
                    System.out.println(principal.getSubject());
                    System.out.println("-----------------DISCONNNNNECTED-----------------");
                })
                .subscribe();
    }