In this tutorial, we will explore how to use Simple (STOMP) over WebSocket for real-time communication in a Spring Boot application. STOMP is a simple text-based protocol that provides message headers and allows you to send messages to specific destinations. It is commonly used with WebSockets to enable real-time messaging between clients and servers.
Before we begin, ensure you have the following:
First, create a new Spring Boot project using Spring Initializr. Choose the following options:
com.examplestomp-websocket-demostomp-websocket-demoDemo project for using STOMP over WebSockets in Spring Bootcom.example.stompwebsocketdemoAdd the following dependencies:
Click "Generate" to download the project files, then import them into your IDE.
Create a configuration class to set up the WebSocket message broker:
package com.example.stompwebsocketdemo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// Enable a simple memory-based message broker to relay messages between connected clients
config.enableSimpleBroker("/topic");
// Define the prefix for application destinations
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// Register STOMP endpoint "/ws" and enable SockJS fallback options
registry.addEndpoint("/ws").withSockJS();
}
}
Create a controller to handle messages sent from clients:
package com.example.stompwebsocketdemo.controller;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class MessageController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public String greeting(String message) throws Exception {
Thread.sleep(1000); // Simulate delay
return "Hello, " + message + "!";
}
}
Create a new directory src/main/resources/templates and add an HTML file index.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>STOMP over WebSocket Demo</title>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
<script type="text/javascript">
var stompClient = null;
function connect() {
var socket = new SockJS('/ws');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
console.log("Disconnected");
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {}, JSON.stringify({'name': name}));
}
function showGreeting(message) {
var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(message));
response.appendChild(p);
}
</script>
</head>
<body onload="connect();">
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! WebSocket relies on Javascript being enabled.</h2></noscript>
<div>
<div>
<label for="name">What is your name?</label><br/>
<input type="text" id="name"/>
<button onclick="sendName();">Send</button>
<p id="response"></p>
</div>
</div>
</body>
</html>
Run your Spring Boot application using your IDE or by executing:
mvn spring-boot:run
Navigate to http://localhost:8080 in your browser. You should see a simple form where you can enter your name and send it to the server. The server will respond with a greeting message, which will be displayed on the page.
In this tutorial, we have learned how to set up STOMP over WebSockets in a Spring Boot application for real-time communication. This setup allows you to build interactive applications with features like live updates and instant messaging. By following the best practices outlined above, you can ensure your application is secure, scalable, and performant.
Feel free to explore more advanced topics such as integrating with message brokers, handling complex message structures, and implementing robust error handling mechanisms to enhance your real-time communication capabilities in Spring Boot applications.