Reactive WebSocket

Spring WebFlux includes a reactive WebSocket client and server support based on the Java WebSocket API.

On the server, create WebSocketHandlerAdapter, and then map each of those handlers to the URL. Since we don't cover WebSocket in our sample application, let's go into a bit more detail:

public class MovieWebSocketHandler implements WebSocketHandler {
@Override
public Mono<Void> handle(WebSocketSession session) {
// ...
}
}

The handle() method takes in the WebSocketSession object and returns Mono<Void> when the handling of session is complete. WebSocketSession handles inbound and outbound messages using the Flux<WebSocketMessage> receive() and Mono<Void> send(Publisher<WebSocketMessage>) methods, respectively.

In the web application Java configuration, declare a bean for WebSocketHandlerAdpater and create another bean to map the URL to the appropriate WebSocketHandler, as shown in the following code snippet:

@Configuration
static class WebApplicationConfig {
@Bean
public HandlerMapping webSockerHandlerMapping() {
Map<String, WebSocketHandler> map = new HashMap<>();
map.put("/movie", new MovieWebSocketHandler());

SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setUrlMap(map);
return mapping;
}
@Bean
public WebSocketHandlerAdapter handlerAdapter() {
return new WebSocketHandlerAdapter();
}
}

Spring WebFlux also provides WebSocketClient and has abstractions for all of the web servers discussed earlier, such as Netty, Jetty, and so on. Use appropriate server abstractions and create the client, as shown in the following code snippet:

WebSocketClient client = new ReactorNettyWebSocketClient();
URI url = new URI("ws://localhost:8080/movie");
client.execute(url, session ->
session.receive()
.doOnNext(System.out::println)
.then());

In the client code, we can now subscribe to the WebSocket, endpoint and listen to messages and do the needful (basic WebSocket implementation). The code snippet for such a client on the frontend is as follows:

<script>
var clientWebSocket = new WebSocket("ws://localhost:8080/movie");
clientWebSocket.onopen = function() {
// Logic as needed
}
clientWebSocket.onclose = function(error) {
// Logic as needed
}
clientWebSocket.onerror = function(error) {
// Logic as needed
}
clientWebSocket.onmessage = function(error) {
// Logic as needed
}
</script>

To keep the chapter focused and concise, we will not go over WebSocket security provided by Spring Security. In the last chapter of this book, we will quickly cover the WebSocket security, using an example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.93.137