java
48 lines · 8 steps
Real-time chat over STOMP WebSockets in Spring
A Spring WebSocket config plus a controller that routes STOMP messages and broadcasts presence updates to subscribed clients.
Explained by
highlit
1@Configuration
2@EnableWebSocketMessageBroker
3public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
4
5 @Override
6 public void registerStompEndpoints(StompEndpointRegistry registry) {
7 registry.addEndpoint("/ws")
8 .setAllowedOriginPatterns("https://app.example.com")
9 .withSockJS();
10 }
11
12 @Override
13 public void configureMessageBroker(MessageBrokerRegistry registry) {
14 registry.setApplicationDestinationPrefixes("/app");
15 registry.enableSimpleBroker("/topic", "/queue");
16 registry.setUserDestinationPrefix("/user");
17 }
18}
19
20@Controller
21public class ChatController {
22
23 private final SimpMessagingTemplate messagingTemplate;
24
25 public ChatController(SimpMessagingTemplate messagingTemplate) {
26 this.messagingTemplate = messagingTemplate;
27 }
28
29 @MessageMapping("/rooms/{roomId}/send")
30 public void handleMessage(@DestinationVariable String roomId,
31 @Payload ChatMessage message,
32 Principal principal) {
33 var outgoing = new ChatMessage(
34 principal.getName(),
35 message.content(),
36 Instant.now());
37
38 messagingTemplate.convertAndSend("/topic/rooms/" + roomId, outgoing);
39 }
40
41 @EventListener
42 public void onDisconnect(SessionDisconnectEvent event) {
43 var accessor = StompHeaderAccessor.wrap(event.getMessage());
44 String user = accessor.getUser() != null ? accessor.getUser().getName() : "unknown";
45 messagingTemplate.convertAndSend("/topic/presence",
46 Map.of("user", user, "status", "OFFLINE"));
47 }
48}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A message broker with destination prefixes cleanly separates client-to-server calls from server-to-client broadcasts.
- 2SimpMessagingTemplate lets any Spring bean push messages to subscribers without holding a socket reference.
- 3Listening for lifecycle events like disconnects turns raw connection state into meaningful presence signals.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/real-time-chat-over-stomp-websockets-in-spring-explained-java-8fba/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.