WebSocket with Spring Boot and SockJS
In this tutorial, you will learn about WebSocket with Spring Boot and SockJS. We cover key concepts, practical examples, and best practices to help you master this topic.
Spring Boot provides WebSocket support through STOMP (Simple Text Oriented Messaging Protocol) and SockJS for fallback. STOMP provides a pub/sub model with destinations similar to JMS. SockJS enables WebSocket emulation when WebSocket is unavailable.
What You'll Learn
- Spring WebSocket configuration
- STOMP Message Broker and destinations
- @MessageMapping and @SendTo annotations
- SockJS fallback for browser compatibility
- Authentication with Spring Security
Why It Matters
Spring Boot is the leading Java framework. Its WebSocket support integrates with Spring Security, Spring Messaging, and transactional management.
Real-World Use
Financial trading platforms use Spring WebSocket for real-time price feeds. Enterprise applications use STOMP for topic-based messaging. Spring-based Microservices often use WebSocket for event-driven communication.
flowchart LR
Client[STOMP Client] --> SockJS[SockJS / WebSocket]
SockJS --> WebSocketConfig[WebSocket Config]
WebSocketConfig --> MessageBroker[Message Broker]
MessageBroker --> AppDestination[/app/...]
MessageBroker --> TopicDestination[/topic/...]
AppDestination --> Controller[@MessageMapping]
Controller --> TopicDestination
Teacher Mindset
Spring WebSocket uses STOMP as a messaging protocol on top of WebSocket. Annotate handler methods with @MessageMapping. Use SimpMessagingTemplate for server-side broadcasts. Configure destinations with /app/ and /topic/ prefixes.
Code Examples
// Example 1: WebSocket configuration
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("*")
.withSockJS();
}
}
// Example 2: STOMP message handler
@Controller
public class ChatController {
@MessageMapping("/chat.send")
@SendTo("/topic/public")
public ChatMessage sendMessage(ChatMessage message) {
return new ChatMessage(
message.getSender(),
message.getContent(),
LocalDateTime.now().toString()
);
}
@MessageMapping("/chat.join")
@SendTo("/topic/public")
public ChatMessage joinRoom(ChatMessage message,
SimpMessageHeaderAccessor headerAccessor) {
headerAccessor.getSessionAttributes().put("username", message.getSender());
return new ChatMessage(
"System",
message.getSender() + " joined the chat",
LocalDateTime.now().toString()
);
}
}
// Example 3: STOMP client in JavaScript
const socket = new SockJS('http://localhost:8080/ws');
const stompClient = Stomp.over(socket);
stompClient.connect({}, (frame) => {
console.log('Connected:', frame);
stompClient.subscribe('/topic/public', (message) => {
const chat = JSON.parse(message.body);
showMessage(chat);
});
stompClient.send('/app/chat.join', {},
JSON.stringify({ sender: username, content: 'joined' })
);
});
function sendMessage() {
stompClient.send('/app/chat.send', {},
JSON.stringify({ sender: username, content: input.value })
);
}
Common Mistakes
- Not enabling the simple broker with enableSimpleBroker
- Forgetting to set application destination prefixes
- Using SockJS without including the SockJS client library
- Not configuring allowed origins for CORS
- Mixing STOMP destinations between /app and /topic incorrectly
Practice
- Configure a Spring Boot WebSocket endpoint with simple broker.
- Create a @MessageMapping handler that broadcasts to a topic.
- Add SockJS fallback support.
- Implement a STOMP JavaScript client.
- Challenge: Add Spring Security authentication that passes the user to WebSocket sessions.
FAQ
Mini Project
Build a Spring Boot chat application with: STOMP WebSocket config with SockJS, @MessageMapping handler for sending messages, @SendTo for broadcasting to /topic/public, SimpMessagingTemplate for private messages, and a simple JavaScript STOMP client.
What's Next
Next, you will learn about WebSocket sticky sessions for load-balanced deployments.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro