WebSocket support

WebSocket is a protocol that allows full-duplex, two-way communication between a server and a client. While establishing the connection, it uses HTTP for the initial handshake. Once done, it will request a protocol upgrade. The Spring WebFlux framework supports reactive WebSocket communication between a client and server based on  the Java WebSocket API. Defining WebSocket is a two-step process as follows:

  • Define the handler to manage the WebSocket request
  • Define mapping to access  the specific handler

In WebFlux, the WebSockets are handled by implementing the WebSocketHandler interface. It has one method calledhandle(). It is provided with the object of WebSocketSession every time a connection is established to the handler. As its name suggests,  WebSocketSession represents the connection formed by a single client. 

Two separate streams  accessible through the receive() and send() methods of the Flux type, are associated with WebSocketSession for handling incoming requests and outgoing messages respectively. We will first define  handler mapping as follows:

 @Autowired
SampleWebSocketHandler studentWebSocketHandler;

@Bean
public HandlerMapping webSockertHandlerMapping() {
Map<String, WebSocketHandler> map = new HashMap<>();
map.put("/student", studentWebSocketHandler);

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

The @Bean annotated method webSockertHandlerMapping is used to map our custom handler with a specific URL pattern by which it can be accessible. The SampleWebSocketHandler  custom handler is injected with the @Autowired annotation and looks as follows:

@Component
public class SampleWebSocketHandler implements WebSocketHandler{

private ObjectMapper objMapper = new ObjectMapper();

@Autowired
StudentMongoRepository studentMongoRepository;

@Override
public Mono<Void> handle(WebSocketSession webSocketSession) {
Flux<Student> allStudentSource = studentMongoRepository.findAll();
System.out.println(" ****** Incoming messages ****** ");
webSocketSession.receive().subscribe(System.out::println);

System.out.println(" ****** Sending Student data ****** ");
return webSocketSession.send(allStudentSource.map(student->{
return writeValueAsSTring(student);
}).map(webSocketSession::textMessage)
);
}

private String writeValueAsSTring(Object obj) {
try {
return objMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return "No data";
}
}

The  SampleWebSocketHandler class provides an implementation of the WebSocketHandler interface with the handle() method. In that method, we are simply fetching all student data from StudentMongoRepository and calling the send() method on WebSocketSession. In the send() method, we first convert the Student object to JSON string with ObjectMapper and finally call the textMessage() method of WebSocketSession to convert it to WebSocketMessage.

Next, is to create the client. We will write client code in JavaScript and call the server from the browser to see how the stream data is received one by one. You can create one HTML file with the following code.

<html>
<body>
Hello
</body>
<script>
var socket = new WebSocket('ws://localhost:8080/student');
socket.addEventListener('message', function (event) {
window.alert('message from server: ' + event.data);
});
</script>
</html>

Almost all modern browsers support WebSocket communication. Open this HTML in a browser and you will see student data one by one with a browser alert. This is how WebSocket communication happens in the reactive paradigm of Spring WebFlux. 

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

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