Spring Reactive Websocket - Sending Messages Dynamically

Viewed 25

I'm trying to implement a basic client for WebSocket in Java using ReactorNettyWebSocketClient. I've already created a basic WebSocket service that works as intended (hosted on localhost:8080). My code looks as follows:

public static void main(String[] args) throws InterruptedException {
    ReactorNettyWebSocketClient client = new ReactorNettyWebSocketClient();
    
    Mono<Void> connect = client.execute(
            URI.create("ws://localhost:8080/app"), handler0()).subscribe();
    
    for (;;);
}

private static WebSocketHandler handler0() {    
    WebSocketHandler handler = session -> {
        return session.send(newMsg("hello world", session))
                .thenMany(session.receive().map(WebSocketMessage::getPayloadAsText))
                .then();
    };
    
    return handler;

}

Everything here works as intended. However, I'm having trouble understanding how I can repeatedly listen for and respond to messages x number of times rather than do it just once. I could call execute() in a loop, however, it appears it establishes a new connection every time which seems to defeat the purpose of using Websocket.

I usually would do something like this when I'd use STOMP, however client.execute() returns a Mono< Void > as shown above.

How would I achieve this?

0 Answers
Related