Real-Time WebSockets and Messaging in Spring Boot [Java Spring Boot Mastery Series – Part 16]
Real-time communication allows servers to push updates to clients instantly. Spring Boot supports this using WebSockets and STOMP messaging. This is useful for:
- Live chat apps 🗨️
- Stock or price updates 📈
- Notification systems 🔔
🚀 What Are WebSockets?
WebSockets provide bi-directional, full-duplex communication over a single, long-lived connection between client and server.
Unlike REST (request-response), WebSockets push data to the client without being asked.
🛠️ 1. Add Required Dependencies
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
For messaging with STOMP and SockJS:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
🔧 2. WebSocket Configuration
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic"); // topic to broadcast messages
config.setApplicationDestinationPrefixes("/app"); // incoming messages
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOriginPatterns("*").withSockJS();
}
}
📝 Explanation:
/ws: WebSocket endpoint for clients./app: Application prefix for incoming messages./topic: Prefix for outgoing (broadcast) messages.
🧠 3. Create Message Model
public class ChatMessage {
private String sender;
private String content;
private String timestamp;
// Getters/Setters
}
🧩 4. Controller to Handle Messages
@Controller
public class ChatController {
@MessageMapping("/chat") // Maps to /app/chat
@SendTo("/topic/messages") // Clients subscribe to /topic/messages
public ChatMessage sendMessage(ChatMessage message) {
message.setTimestamp(LocalDateTime.now().toString());
return message;
}
}
📝 Clients send to /app/chat, and messages are broadcast to /topic/messages.
🌐 5. HTML + JavaScript WebSocket Client (Basic)
<!DOCTYPE html>
<html>
<head>
<title>Chat App</title>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/stomp.min.js"></script>
</head>
<body>
<div id="messages"></div>
<input type="text" id="messageInput" />
<button onclick="sendMessage()">Send</button>
<script>
var socket = new SockJS('/ws');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/messages', function (messageOutput) {
const msg = JSON.parse(messageOutput.body);
document.getElementById('messages').innerHTML += '<p>' + msg.sender + ': ' + msg.content + '</p>';
});
});
function sendMessage() {
var content = document.getElementById('messageInput').value;
stompClient.send("/app/chat", {}, JSON.stringify({'sender': 'User', 'content': content}));
}
</script>
</body>
</html>
🧪 Test It
- Run the Spring Boot application.
- Open multiple browser tabs with the above HTML.
- Send a message from one tab — others receive it instantly. 🎉
🔐 Bonus: Securing WebSockets
Use Spring Security to:
- Authenticate WebSocket connections.
- Authorize subscriptions per user or role
📌 Summary
| Feature | WebSockets with Spring Boot |
|---|---|
| Protocol | WebSocket + STOMP |
| Libraries | Spring WebSocket, SockJS, STOMP.js |
| Use Cases | Live chat, notifications, dashboards |
| Security | Spring Security + Message Interceptor |
➡️ Next Up: Part 17 – Spring Boot Admin & Monitoring Microservices
