Video in progress

What is wrong in the WebFlux WebSocketHandler below? The client receives messages, but what it sends doesn't appear in the server log.

@Override
public Mono<Void> handle(WebSocketSession session) {
    session.receive()
           .map(WebSocketMessage::getPayloadAsText)
           .doOnNext(log::info)
           .subscribe();
    return session.send(prices.stream().map(session::textMessage));
}

The subscribe() on the receive() stream is done separately, and handle returns only the send Mono. The framework waits only for the returned Mono to complete; both streams must be combined into a single Mono.

📖 Answer

In reactive WebSocket the rule is simple: when the Mono<Void> returned by handle completes, the session is closed. Calling subscribe() manually inside is a classic mistake in reactive code. That stream slips out of the framework's control: errors vanish, cancellation doesn't work, and resources aren't cleaned up when the session closes. On some servers in this situation the inbound stream isn't read at all, or is cut at an unexpected moment.

The correct version is to combine both directions:

@Override
public Mono<Void> handle(WebSocketSession session) {
    Mono<Void> input = session.receive()
            .map(WebSocketMessage::getPayloadAsText)
            .doOnNext(log::info)
            .then();

    Mono<Void> output = session.send(
            prices.stream().map(session::textMessage));

    return Mono.when(input, output);
}

Mono.when waits for both to finish. Mono.zip isn't right here: a Mono<Void> emits no value, and zip cancels the others when one source completes empty. If the session should close when either one finishes (for example, stop the output too when the client disconnects), Mono.firstWithSignal(input, output) fits.

One more subtle point: call getPayloadAsText() inside map, that is, immediately. The payload is a DataBuffer, and if you read it later it may already have been released.

And don't do blocking work inside doOnNext: that's a Netty event loop thread. If you need to write to a DB, use flatMap with a reactive driver, or publishOn(Schedulers.boundedElastic()).