Interface WebSocketHandler
- All Known Implementing Classes:
ContextWebSocketHandler
- On the server side,
WebSocketHandleris mapped to requests withSimpleUrlHandlerMappingandWebSocketHandlerAdapter. - On the client side,
WebSocketHandleris passed into theWebSocketClientexecute method.
session.receive() handles inbound
messages, while session.send
sends outbound messages. Below is an example of handling inbound messages
and responding to every message:
class ExampleHandler implements WebSocketHandler {
@Override
public Mono<Void> handle(WebSocketSession session) {
Flux<WebSocketMessage> output = session.receive()
.doOnNext(message -> {
// Imperative calls without a return value:
// perform access checks, log, validate, update metrics.
// ...
})
.concatMap(message -> {
// Async, non-blocking calls:
// parse messages, call a database, make remote calls.
// Return the same message, or a transformed value
// ...
});
return session.send(output);
}
}
If processing inbound and sending outbound messages are independent streams, they can be joined together with the "and" operator:
class ExampleHandler implements WebSocketHandler {
@Override
public Mono<Void> handle(WebSocketSession session) {
Mono<Void> input = session.receive()
.doOnNext(message -> {
// ...
})
.concatMap(message -> {
// ...
})
.then();
Flux<String> source = ... ;
Mono<Void> output = session.send(source.map(session::textMessage));
return input.and(output);
}
}
A WebSocketHandler must compose the inbound and outbound streams
into a unified flow and return a Mono<Void> that reflects the
completion of that flow. That means there is no need to check if the
connection is open, since Reactive Streams signals will terminate activity.
The inbound stream receives a completion/error signal, and the outbound
stream receives a cancellation signal.
- Since:
- 5.0
- Author:
- Rossen Stoyanchev
-
Method Summary
Modifier and TypeMethodDescriptionReturn the list of sub-protocols supported by this handler.reactor.core.publisher.Mono<Void> handle(WebSocketSession session) Invoked when a new WebSocket connection is established, and allows handling of the session.
-
Method Details
-
getSubProtocols
-
handle
Invoked when a new WebSocket connection is established, and allows handling of the session.See the class-level doc and the reference manual for more details and examples of how to handle the session.
- Parameters:
session- the session to handle- Returns:
- indicates when application handling of the session is complete, which should reflect the completion of the inbound message stream (i.e. connection closing) and possibly the completion of the outbound message stream and the writing of messages
-