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