Sven Loesekann
Sven Loesekann

Reputation: 63

Spring Websocket Client Reactor times out

I am trying to build a client for the Websocket "wss://echo.websocket.org". The codes uses Spring 5 with the ReactorNettyWebSocketClient().

public class WsClient {
 public static void main(String[] args) throws InterruptedException {
    WebSocketClient client = new ReactorNettyWebSocketClient();     
    client.execute(URI.create("wss://echo.websocket.org"), 
            new ClientWebSocketHandler()).block(Duration.ofSeconds(15));
    System.out.println("End");
}

    static class ClientWebSocketHandler implements WebSocketHandler {

    @Override
    public Mono<Void> handle(WebSocketSession session) {            
        WebSocketMessage textMessage = session.textMessage("{\"event\":\"ping\"}");
        session.send(Mono.just(textMessage));
        String payloadAsText = session.receive().blockFirst().getPayloadAsText();
        System.out.println(payloadAsText);
        return Mono.empty();
    }

    }
}

The code times out after 15 seconds. It should send a ping message and I would expect the ping message back.

Upvotes: 1

Views: 1017

Answers (1)

Sven Loesekann
Sven Loesekann

Reputation: 26

I found a solution:

public class WsClient {

public static void main(String[] args) throws InterruptedException {
    WebSocketClient client = new ReactorNettyWebSocketClient();     
    client.execute(URI.create("wss://echo.websocket.org"), 
            session -> session.send(Mono.just(
                    session.textMessage("{\"event\":\"ping\"}")))
            .thenMany(session
                      .receive()
                      .map(WebSocketMessage::getPayloadAsText)
                      .log())
                    .then()).block(Duration.ofSeconds(10));     
    System.out.println("End");
}

}

It is based on: https://stackify.com/reactive-spring-5/

Upvotes: 1

Related Questions