Reactive WebSockets with Spring 5 - how to get ini

2019-06-25 00:25发布

问题:

I followed that tutorial (specifically the part with the Browser WebSocket Client): http://www.baeldung.com/spring-5-reactive-websockets Everything works fine.

I would like to go a step further and having my handler behave according to a parameter sent from the client side. On connection the client is sending a message ("event-me-from-browser"):

var clientWebSocket = new WebSocket("ws://localhost:8080/event-emitter");
clientWebSocket.onopen = function() {
    console.log("clientWebSocket.onopen", clientWebSocket);
    console.log("clientWebSocket.readyState", "websocketstatus");
    clientWebSocket.send("event-me-from-browser");
}

I tried to retrieve that message on server side (java):

@Override
public Mono<Void> handle(WebSocketSession webSocketSession) {

   webSocketSession.receive().handle((pWebSocketMessage, pSynchronousSink) -> System.out.println(pWebSocketMessage.getPayloadAsText()));

   return webSocketSession.send(Flux.fromStream(Stream.generate(() -> getData()))
         .delayElements(Duration.ofMillis(50))
         .map(webSocketSession::textMessage))
         .and(webSocketSession.receive()
               .map(WebSocketMessage::getPayloadAsText)
               .log());
}

But it does not work.

Any idea? What did I do wrong?

回答1:

Excluding tomcat dependency (and using netty instead) will work:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <!-- Exclude the Tomcat dependency -->
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>


回答2:

I had the same issue. I believe it may be do to the modules that Spring Boot auto-imports, specifically Tomcat.

I followed this video https://www.youtube.com/watch?v=GlvyHIqT3K4 and websockets worked right away using a stack of:

  • Netty (not Tomcat)
  • Spring Boot 2.0.x spring-boot-starter-parent
  • Spring Integration spring-boot-starter-integration
  • Spring WebFlux (Reactive) spring-boot-starter-webflux