WebSockets¶
WebSockets provide full-duplex, persistent communication between client and server over a single TCP connection. Unlike HTTP (request-response), WebSockets allow the server to push data to clients in real-time. Use cases: chat, live dashboards, notifications, collaborative editing, gaming. Spring supports WebSockets via @MessageMapping with STOMP protocol over SockJS.
Key Concepts¶
Deep Dive: HTTP vs WebSocket
| Feature | HTTP | WebSocket |
|---|---|---|
| Communication | Request-response | Full-duplex |
| Connection | New per request (or keep-alive) | Persistent |
| Direction | Client → Server | Bidirectional |
| Overhead | Headers on every request | Minimal after handshake |
| Use case | REST APIs, web pages | Real-time data |
WebSocket handshake (HTTP upgrade):
Deep Dive: Spring WebSocket with STOMP
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/topic");
}
}
@Controller
public class ChatController {
@MessageMapping("/chat.send")
@SendTo("/topic/messages")
public ChatMessage send(ChatMessage message) {
return message;
}
}
Deep Dive: Alternatives
| Technique | Description | Use When |
|---|---|---|
| Polling | Client requests periodically | Simple, low frequency |
| Long Polling | Server holds request until data | Moderate real-time |
| SSE (Server-Sent Events) | Server → Client stream only | One-way updates |
| WebSocket | Full-duplex | True real-time, bidirectional |
Common Interview Questions
- What are WebSockets? How do they differ from HTTP?
- How does the WebSocket handshake work?
- What is STOMP? SockJS?
- What is the difference between WebSocket and SSE?
- When would you use polling vs WebSockets?