Skip to content
Spring Boot WebSocket & STOMP: Complete Message Flow & Architecture Guide

Spring Boot WebSocket & STOMP: Complete Message Flow & Architecture Guide

This article explains Spring Boot's WebSocket and STOMP integration, covering connection establishment, message routing architecture, broker types, destination prefixes, and practical code examples for real-time features like chat and notifications.

Java Tech Workshop
Java Tech Workshop
Java Tech Workshop

Why WebSocket Needs STOMP

WebSocket provides a full-duplex TCP long connection after HTTP upgrade, but it is only a transport pipe. It lacks message routing, a pub/sub model, a standard frame format, and cluster-wide broadcast capabilities. Raw JSR-356 code requires manual session management, message parsing, and fan-out loops.

STOMP (Simple Text Oriented Messaging Protocol) adds an application-layer protocol on top of WebSocket. It introduces destinations (e.g., /topic/notice), SUBSCRIBE/SEND frames, a Broker for routing, and standardized frame commands (CONNECT, SUBSCRIBE, SEND, MESSAGE, UNSUBSCRIBE, DISCONNECT, ERROR). STOMP can run over WebSocket or TCP; Spring commonly uses STOMP over WebSocket.

Connection Establishment

WebSocket Handshake

Client sends HTTP request with upgrade headers:

GET /ws/chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

Server responds with 101 Switching Protocols:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

After upgrade, communication uses WebSocket frames (text, binary, ping/pong, close).

WebSocket Frame Types

Text frame : transports strings (JSON, etc.)

Binary frame : transports byte streams

Ping/Pong : heartbeat keep-alive

Close : closes the connection

STOMP Connection Flow

Over the WebSocket connection, client sends a STOMP CONNECT frame:

CONNECT
accept-version:1.2
heart-beat:10000,10000

Server replies with CONNECTED, then SUBSCRIBE/SEND are allowed.

SockJS Fallback

For environments without WebSocket support, Spring provides SockJS which falls back to long-polling or streaming while exposing a unified client API.

Spring Architecture: Broker, Channels & Message Mapping

Core Components

WebSocketMessageBrokerConfigurer : entry interface for configuring endpoints, broker, channels

MessageBrokerRegistry : configures simple broker or external broker relay

SubscribableChannel : inbound/outbound message channels

StompSubProtocolHandler : parses STOMP frames, converts to/from WebSocket messages

@MessageMapping : maps SEND frames to controller methods

SimpMessagingTemplate : server-side active message sending to destinations

SimpUserRegistry : maintains online users and sessions

Two Broker Types

Built-in SimpleBroker : in-memory, maintains subscriptions and broadcasts. Suitable for simple broadcasts, demos, small-scale apps. No persistence, no cross-node clustering.

External StompBrokerRelay : connects to RabbitMQ, ActiveMQ, Redis, etc. Spring acts as relay; broker handles subscription management and broadcasting. Used in production clusters.

Destination Prefix Conventions

/app : client-to-application-method destinations, handled by @MessageMapping /topic : broadcast topics (one-to-many), used for announcements, global pushes

/queue : point-to-point queues, directed messages (often with /user)

/user : per-user exclusive destinations, used with @SendToUser, private chat

Message Channels

ClientInboundChannel : client messages enter here, pass through interceptors (auth, logging) then dispatch

ClientOutboundChannel : server messages exit here to clients

Channels are synchronous by default; can configure thread pools for async processing

Complete Message Flow Breakdown

Overall Chain

Browser (SockJS + STOMP.js)
  │ ① WebSocket handshake → 101
  │ ② STOMP CONNECT
  ▼
WebSocket Endpoint (StompEndpointRegistry)
  │
  ▼
StompSubProtocolHandler: decode STOMP frames
  │
  ▼
ClientInboundChannel (interceptors: auth, intercept)
  │
  ├─ SUBSCRIBE → Broker records subscription
  ├─ SEND /app/xxx → @MessageMapping method
  │               │ return value
  │               ▼
  │         @SendTo / SimpMessagingTemplate
  │               │
  ▼               ▼
      ClientOutboundChannel → Broker routing
                                 │
                                 ▼
                          Subscribers receive MESSAGE frame

Scenario 1: Broadcast Message

Client subscribes to /topic/notice.

Client SENDs to /app/notice, triggering @MessageMapping method.

Method return value via @SendTo("/topic/notice") goes to Broker.

Broker delivers MESSAGE frame to all subscribers of /topic/notice.

Scenario 2: Server-Initiated Push

Backend code calls SimpMessagingTemplate directly:

messagingTemplate.convertAndSend("/topic/notice", new NoticeVO("新公告"));

Message enters outbound channel → Broker → all subscribers.

Scenario 3: Point-to-Point User Message

Destinations prefixed with /user/ combined with user identifier. @SendToUser replies only to the requesting user.

Server pushes to specific user: convertAndSendToUser(userId, "/queue/msg", payload).

Spring resolves /user/queue/msg to that user's exclusive queue destination.

Source-Level View: How Messages Find Methods

Inbound SEND frame becomes Message<byte[]> with destination header. @MessageMapping methods are matched by SimpAnnotationMethodMessageHandler, similar to MVC's HandlerMapping:

Match by destination path.

Resolve method parameters ( @Payload, @Headers, Principal, etc.).

Invoke via reflection.

Return value handled by return-value handlers ( @SendTo or template) to Broker.

Code Examples: Config, Controller, Frontend & Push

Dependencies (Spring Boot 3.x)

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

WebSocket + STOMP Configuration

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws/chat")
            .setAllowedOriginPatterns("*")
            .withSockJS();
  }

  @Override
  public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.setApplicationDestinationPrefixes("/app");
    registry.enableSimpleBroker("/topic", "/queue");
    registry.setUserDestinationPrefix("/user");
    // Production: external broker relay
    // registry.enableStompBrokerRelay("/topic", "/queue")
    //   .setRelayHost("rabbitmq-host")
    //   .setRelayPort(61613)
    //   .setClientLogin("guest")
    //   .setClientPasscode("guest");
  }

  @Override
  public void configureClientInboundChannel(ChannelRegistration registration) {
    registration.interceptors(new AuthChannelInterceptor());
  }
}

Message Controller

@Controller
public class ChatController {

  private final SimpMessagingTemplate messagingTemplate;

  public ChatController(SimpMessagingTemplate messagingTemplate) {
    this.messagingTemplate = messagingTemplate;
  }

  @MessageMapping("/chat")
  @SendTo("/topic/chat")
  public ChatMessage broadcast(ChatMessage message, Principal principal) {
    message.setFrom(principal.getName());
    return message;
  }

  @MessageMapping("/private")
  @SendToUser("/queue/reply")
  public ChatMessage replyToUser(ChatMessage message, Principal principal) {
    message.setFrom(principal.getName());
    return message;
  }

  public void pushToUser(String userId, ChatMessage message) {
    messagingTemplate.convertAndSendToUser(
      userId, "/queue/msg", message);
  }
}

Message Payload

@Data
public class ChatMessage {
  private String from;
  private String to;
  private String content;
  private Long timestamp;
}

Frontend (SockJS + STOMP.js)

const socket = new SockJS('/ws/chat');
const stompClient = Stomp.over(socket);

stompClient.connect({}, function (frame) {
  stompClient.subscribe('/topic/chat', function (msg) {
    const body = JSON.parse(msg.body);
    console.log('Broadcast received:', body);
  });

  stompClient.subscribe('/user/queue/reply', function (msg) {
    const body = JSON.parse(msg.body);
    console.log('Private message:', body);
  });

  stompClient.send('/app/chat', {},
    JSON.stringify({ content: 'Hello', timestamp: Date.now() }));
});

Inbound Auth Interceptor Example

public class AuthChannelInterceptor implements ChannelInterceptor {

  @Override
  public Message<?> preSend(Message<?> message, MessageChannel channel) {
    StompHeaderAccessor accessor =
      MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

    if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())) {
      String token = accessor.getFirstNativeHeader("Authorization");
      // Validate token, then set user into Principal
      // accessor.setUser(new StompPrincipal(userId));
    }
    return message;
  }
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Real-time MessagingSpring BootWebSocketSTOMPMessage BrokerSockJSSpring MessagingSimpMessagingTemplate
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.