WebSocket for real-time communication

David Kumar Jan 2026
3 tabs
package com.example.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // Enable simple broker for topics
        registry.enableSimpleBroker("/topic", "/queue");
        // Prefix for messages from client to server
        registry.setApplicationDestinationPrefixes("/app");
        // Prefix for user-specific messages
        registry.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
            .setAllowedOrigins("http://localhost:3000")
            .withSockJS();
    }
}
3 files · java Explain with highlit

WebSocket enables full-duplex communication between client and server. Spring WebSocket supports STOMP protocol over WebSocket. I configure message brokers for pub-sub messaging. @MessageMapping handles incoming messages. SimpMessagingTemplate sends messages to clients. Topics broadcast to multiple subscribers; queues send to individual users. Security integrates with Spring Security. SockJS provides fallback for browsers without WebSocket support. WebSocket connections persist, enabling push notifications, live updates, and chat applications. Connection lifecycle hooks manage setup and cleanup. Message conversion supports JSON, binary, and custom formats. WebSocket excels for real-time dashboards, collaborative tools, and gaming. Proper error handling and heartbeat mechanisms ensure connection stability.