Examples of use ReactorNettyWebSocketClient

后端 未结 2 1818
礼貌的吻别
礼貌的吻别 2021-01-01 05:00

New Spring has some WebSocketClient example on Spring documentation.

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


        
相关标签:
2条回答
  • 2021-01-01 05:52

    I assume you are using an "echo" service. In order to get some messages from the service, you have to push them into the websocket and the service will "echo" them back to you.

    In your example code you are writing only a single element to the websocket. As soon as you push more messages into the socket you will get more back.

    I adapted the code to connect to ws://echo.websocket.org instead of a local service. When you browse to /stream you see every second a new message appear.

    @GetMapping(path = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> getStreaming() throws URISyntaxException {
    
        Flux<String> input = Flux.<String>generate(sink -> sink.next(String.format("{ message: 'got message', date: '%s' }", new Date())))
            .delayElements(Duration.ofSeconds(1));
    
        WebSocketClient client = new ReactorNettyWebSocketClient();
        EmitterProcessor<String> output = EmitterProcessor.create();
    
        Mono<Void> sessionMono = client.execute(URI.create("ws://echo.websocket.org"), session -> session.send(input.map(session::textMessage))
            .thenMany(session.receive().map(WebSocketMessage::getPayloadAsText).subscribeWith(output).then()).then());
    
        return output.doOnSubscribe(s -> sessionMono.subscribe());
    }
    

    Hope this helps...

    0 讨论(0)
  • 2021-01-01 05:54

    The documentation link above is to the temporary docs from before Spring Framework 5 was released. Currently the reference provides more information about implementing a WebSocketHandler.

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