How to use Spring Reactive WebSocket and transform it into the Flux stream?

前端 未结 1 1261
逝去的感伤
逝去的感伤 2021-02-06 16:41

There is some WebSocketClient example on Spring documentation:

WebSocketClient client = new ReactorNettyWebSocketClient();
client.execute(\"ws://loc         


        
1条回答
  •  感情败类
    2021-02-06 17:21

    Just take a look into that WebSocketSession param of the WebSocketHandler.handle() lambda:

    /**
     * Get the flux of incoming messages.
     */
    Flux receive();
    

    See Spring WebFlux Workshop for more information.

    UPDATE

    Let's try this!

        Mono sessionMono =
                client.execute(new URI("ws://localhost:8080/echo"),
                        session ->
                                Mono.empty()
                                        .subscriberContext(Context.of(WebSocketSession.class, session))
                                        .then());
    
        return sessionMono
                .thenMany(
                        Mono.subscriberContext()
                                .flatMapMany(c -> c
                                        .get(WebSocketSession.class)
                                        .receive()))
                .map(WebSocketMessage::getPayloadAsText);
    

    UPDATE 2

    Or another option but with blocked subscription:

        EmitterProcessor output = EmitterProcessor.create();
    
        client.execute(new URI("ws://localhost:8080/echo"),
                session ->
                        session.receive()
                                .map(WebSocketMessage::getPayloadAsText)
                                .subscribeWith(output)
                                .then())
                .block(Duration.ofMillis(5000));
    
        return output;
    

    UPDATE 3

    The working Spring Boot application on the matter: https://github.com/artembilan/webflux-websocket-demo

    The main code is like:

        EmitterProcessor output = EmitterProcessor.create();
    
        Mono sessionMono =
                client.execute(new URI("ws://localhost:8080/echo"),
                        session -> session.receive()
                                .map(WebSocketMessage::getPayloadAsText)
                                .subscribeWith(output)
                                .then());
    
        return output.doOnSubscribe(s -> sessionMono.subscribe());
    

    0 讨论(0)
提交回复
热议问题