Spring Boot WebSocket: from a raw handler to STOMP messaging

WebSocket keeps one connection open so that the server can send whenever something happens. This page explains the handshake and Spring's two programming models, then runs an echo handler, an authenticated chat room with origin checks, the concurrent send failure and its fix, and a STOMP chat with topics and a broker.

Contents

What WebSocket is and how Spring supports it

HTTP is request and response: the client asks, the server answers, and the server cannot speak first. Chat, live prices, notifications and collaborative editing need the opposite, a server that sends data whenever something happens. WebSocket, defined in RFC 6455, provides that: one long-lived TCP connection on which both sides can send messages at any time.

A WebSocket connection starts as an ordinary HTTP request. The client sends GET with Upgrade: websocket and a random key; the server answers 101 Switching Protocols, and from then on the same TCP connection carries WebSocket frames instead of HTTP. Because the start is HTTP, the handshake passes through the same server, filters and security as other requests, and the same port serves both.

Spring offers two levels of support, both in Spring Framework 7.0 and enabled in Spring Boot by spring-boot-starter-websocket:

WebSocket programming models in Spring
ModelYou writeBest for
Raw WebSocket, @EnableWebSocketA WebSocketHandler that receives and sends text or binary framesSimple protocols, streaming data, one handler per endpoint
STOMP messaging, @EnableWebSocketMessageBroker@MessageMapping methods and destinations such as /topic/pricesChat, notifications, publish and subscribe with many topics
SockJS fallback, withSockJS()Nothing extra on the serverBrowsers or proxies where WebSocket is blocked

Raw WebSocket gives you a pipe and nothing more: no message types, no routing and no subscriptions. STOMP, the Simple Text Oriented Messaging Protocol, adds frames such as CONNECT, SUBSCRIBE and SEND on top of WebSocket, and Spring routes those frames to controller methods and to a message broker. The programs use Spring Boot 4.1, Spring Framework 7.0 and Tomcat 11. They act as their own clients, with the JDK's java.net.http.WebSocket for raw WebSocket and Spring's WebSocketStompClient for STOMP.

A first WebSocket handler

An echo server is the smallest complete exchange: open, send, receive, close. The handler extends TextWebSocketHandler and closes the connection itself when the client says bye, so the close handshake is visible from both sides:

Java
package demo.echo;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@SpringBootApplication
public class EchoSocket {

    static final BlockingQueue<String> SERVER_LOG = new LinkedBlockingQueue<>();

    static class EchoHandler extends TextWebSocketHandler {
        @Override
        public void afterConnectionEstablished(WebSocketSession session) {
            SERVER_LOG.add("server: connection open, path " + session.getUri().getPath());
        }

        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message)
                throws Exception {
            SERVER_LOG.add("server: received \"" + message.getPayload() + "\"");
            session.sendMessage(new TextMessage("echo: " + message.getPayload()));
            if (message.getPayload().equals("bye")) {
                session.close(CloseStatus.NORMAL.withReason("see you"));
            }
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
            SERVER_LOG.add("server: connection closed, " + status);
        }
    }

    @Configuration
    @EnableWebSocket
    static class SocketConfig implements WebSocketConfigurer {
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(new EchoHandler(), "/echo");
        }
    }

    // A client built on the JDK's java.net.http.WebSocket
    static class Client implements WebSocket.Listener {
        final BlockingQueue<String> events = new LinkedBlockingQueue<>();

        @Override
        public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
            events.add("client: received \"" + data + "\"");
            ws.request(1);
            return null;
        }

        @Override
        public CompletionStage<?> onClose(WebSocket ws, int code, String reason) {
            events.add("client: closed by server, code " + code + " \"" + reason + "\"");
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(EchoSocket.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            Client client = new Client();
            WebSocket ws = HttpClient.newHttpClient().newWebSocketBuilder()
                    .buildAsync(URI.create("ws://localhost:" + port + "/echo"), client)
                    .join();
            System.out.println("client: connected, subprotocol \"" + ws.getSubprotocol() + "\"");
            System.out.println(SERVER_LOG.poll(5, TimeUnit.SECONDS));

            for (String text : new String[] {"hello", "bye"}) {
                System.out.println("client: sending \"" + text + "\"");
                ws.sendText(text, true).join();
                System.out.println(SERVER_LOG.poll(5, TimeUnit.SECONDS));
                System.out.println(client.events.poll(5, TimeUnit.SECONDS));
            }
            System.out.println(client.events.poll(5, TimeUnit.SECONDS));
            System.out.println(SERVER_LOG.poll(5, TimeUnit.SECONDS));
        }
    }
}
Output
client: connected, subprotocol ""
server: connection open, path /echo
client: sending "hello"
server: received "hello"
client: received "echo: hello"
client: sending "bye"
server: received "bye"
client: received "echo: bye"
client: closed by server, code 1000 "see you"
server: connection closed, CloseStatus[code=1000, reason=see you]
  • The client connected with an empty subprotocol, since the handler declares none. The server's afterConnectionEstablished ran once the 101 handshake had completed, with the path /echo.
  • Each text message reached handleTextMessage, and session.sendMessage sent the reply on the same connection. Nothing in this code mentions requests or responses: the server could equally send without being asked.
  • After bye, the server called session.close(CloseStatus.NORMAL.withReason("see you")). The client received close code 1000 with the reason, and the server's afterConnectionClosed reported the same status.

@EnableWebSocket and WebSocketConfigurer map handlers to URLs, the way controllers are mapped for HTTP. One handler instance serves every connection to its path, so state for one connection belongs in the WebSocketSession, whose getAttributes() map lives as long as the connection.

Handshakes, origins and broadcasting

A chat room needs three things the echo server lacks: knowing who is connected, refusing unknown users, and sending one message to everyone. The program authenticates with a token in the URL during the handshake, restricts the allowed origin, and keeps a set of open sessions:

Java
package demo.chat;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.net.http.WebSocketHandshakeException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.util.UriComponentsBuilder;

@SpringBootApplication
public class ChatRoom {

    static final Map<String, String> TOKENS = Map.of("t-ana", "ana", "t-ben", "ben");

    // Runs on the HTTP upgrade request, before any WebSocket session exists
    static class TokenInterceptor implements HandshakeInterceptor {
        @Override
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                       WebSocketHandler handler, Map<String, Object> attributes) {
            String token = UriComponentsBuilder.fromUri(request.getURI()).build()
                    .getQueryParams().getFirst("token");
            String user = TOKENS.get(token);
            if (user == null) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return false;                          // the upgrade is refused
            }
            attributes.put("user", user);              // copied into the session
            return true;
        }

        @Override
        public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler handler, Exception exception) {
        }
    }

    static class ChatHandler extends TextWebSocketHandler {
        private final Set<WebSocketSession> sessions = ConcurrentHashMap.newKeySet();

        @Override
        public void afterConnectionEstablished(WebSocketSession session) {
            sessions.add(session);
        }

        @Override
        protected void handleTextMessage(WebSocketSession from, TextMessage message)
                throws Exception {
            String line = from.getAttributes().get("user") + ": " + message.getPayload();
            for (WebSocketSession session : sessions) {
                synchronized (session) {               // one sender at a time per session
                    session.sendMessage(new TextMessage(line));
                }
            }
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
            sessions.remove(session);
        }
    }

    @Configuration
    @EnableWebSocket
    static class SocketConfig implements WebSocketConfigurer {
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(new ChatHandler(), "/chat")
                    .addInterceptors(new TokenInterceptor())
                    .setAllowedOrigins("https://chat.example.com");
        }
    }

    static class Inbox implements WebSocket.Listener {
        final BlockingQueue<String> received = new LinkedBlockingQueue<>();

        @Override
        public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
            received.add(data.toString());
            ws.request(1);
            return null;
        }
    }

    static String base;

    static WebSocket connect(String who, String token, String origin, Inbox inbox) {
        WebSocket.Builder builder = HttpClient.newHttpClient().newWebSocketBuilder();
        if (origin != null) {
            builder.header("Origin", origin);
        }
        try {
            WebSocket ws = builder.buildAsync(
                    URI.create(base + "/chat?token=" + token), inbox).join();
            System.out.println(who + " connects (Origin " + origin + "): open");
            return ws;
        } catch (CompletionException e) {
            String status = e.getCause() instanceof WebSocketHandshakeException h
                    ? "HTTP " + h.getResponse().statusCode() : e.getCause().toString();
            System.out.println(who + " connects (Origin " + origin + "): refused, " + status);
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(ChatRoom.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            base = "ws://localhost:" + port;
            String site = "https://chat.example.com";

            Inbox anaInbox = new Inbox();
            Inbox benInbox = new Inbox();
            WebSocket ana = connect("ana", "t-ana", site, anaInbox);
            WebSocket ben = connect("ben", "t-ben", site, benInbox);
            connect("eve", "stolen", site, new Inbox());
            connect("ana", "t-ana", "https://evil.example.net", new Inbox());
            connect("ana", "t-ana", null, new Inbox());

            ana.sendText("hi Ben", true).join();
            System.out.println("ana's screen: " + anaInbox.received.poll(5, TimeUnit.SECONDS));
            System.out.println("ben's screen: " + benInbox.received.poll(5, TimeUnit.SECONDS));
            ben.sendText("hi Ana", true).join();
            System.out.println("ana's screen: " + anaInbox.received.poll(5, TimeUnit.SECONDS));
            System.out.println("ben's screen: " + benInbox.received.poll(5, TimeUnit.SECONDS));
        }
    }
}
Output
ana connects (Origin https://chat.example.com): open
ben connects (Origin https://chat.example.com): open
eve connects (Origin https://chat.example.com): refused, HTTP 401
ana connects (Origin https://evil.example.net): refused, HTTP 403
ana connects (Origin null): open
ana's screen: ana: hi Ben
ben's screen: ana: hi Ben
ana's screen: ben: hi Ana
ben's screen: ben: hi Ana
  • The HandshakeInterceptor ran on the HTTP upgrade request. For Ana and Ben it found a valid token and stored the user name in the attributes map, which Spring copies into the new session. The chat handler later read user from there to label each message.
  • Eve's unknown token made beforeHandshake set 401 and return false, so the upgrade never happened and the client saw HTTP 401 instead of an open connection.
  • A connection with a valid token but Origin: https://evil.example.net was refused with 403 by the origin check of setAllowedOrigins. Browsers always send Origin on WebSocket handshakes, and they do not apply CORS to WebSocket, so this check is what stops other websites from opening connections with a user's cookies.
  • The connection without any Origin header was accepted. Spring treats a missing origin as a non-browser client, which the token must then authenticate.
  • Both messages reached both screens, including the sender's own, because the handler sends each message to every open session.

By default, Spring allows only the same origin as the server, which suits a page served by the same application. In a real application, authenticate the handshake with the same mechanism as the rest of the API. With Spring Security, the handshake request goes through the security filter chain like any other request; a browser cannot set custom headers on a WebSocket handshake, so tokens are usually sent in a cookie or a query parameter.

The concurrency trap: sending from several threads

The chat handler above wraps each send in synchronized, and that is not decoration. The WebSocket API of Jakarta EE, which Tomcat implements, allows only one send at a time on a session. A price feed that pushes updates from several threads breaks this rule easily. This program sends 200 messages of 64 KB from four threads to one session, first directly and then through Spring's ConcurrentWebSocketSessionDecorator:

Java
package demo.concurrent;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@SpringBootApplication
public class ConcurrentSends {

    static final int THREADS = 4;
    static final int MESSAGES_PER_THREAD = 50;
    static final String PAYLOAD = "x".repeat(64 * 1024);    // 64 KB per message

    // Sends from several threads at once to one session, as a price feed might
    static class FeedHandler extends TextWebSocketHandler {
        @Override
        public void afterConnectionEstablished(WebSocketSession raw) {
            boolean decorate = raw.getUri().getQuery().contains("safe");
            WebSocketSession session = decorate
                    ? new ConcurrentWebSocketSessionDecorator(raw, 10000, 64 * 1024 * 1024)
                    : raw;
            AtomicInteger failures = new AtomicInteger();
            List<String> firstError = new ArrayList<>();
            List<CompletableFuture<Void>> senders = new ArrayList<>();
            for (int t = 0; t < THREADS; t++) {
                senders.add(CompletableFuture.runAsync(() -> {
                    for (int i = 0; i < MESSAGES_PER_THREAD; i++) {
                        try {
                            session.sendMessage(new TextMessage(PAYLOAD));
                        } catch (Exception | Error e) {
                            failures.incrementAndGet();
                            synchronized (firstError) {
                                if (firstError.isEmpty()) {
                                    firstError.add(e.getClass().getSimpleName()
                                            + ": " + e.getMessage());
                                }
                            }
                        }
                    }
                }));
            }
            CompletableFuture.allOf(senders.toArray(CompletableFuture[]::new)).join();
            System.out.println("  server: " + (decorate ? "with" : "without")
                    + " ConcurrentWebSocketSessionDecorator, failed sends: " + failures
                    + (firstError.isEmpty() ? "" : "\n  first error: " + firstError.get(0)));
        }
    }

    @Configuration
    @EnableWebSocket
    static class SocketConfig implements WebSocketConfigurer {
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(new FeedHandler(), "/feed");
        }
    }

    static void listen(int port, String mode) throws Exception {
        int expected = THREADS * MESSAGES_PER_THREAD;
        AtomicInteger received = new AtomicInteger();
        CountDownLatch done = new CountDownLatch(1);
        WebSocket.Listener listener = new WebSocket.Listener() {
            @Override
            public CompletionStage<?> onText(WebSocket ws, CharSequence data, boolean last) {
                if (last && received.incrementAndGet() == expected) {
                    done.countDown();
                }
                ws.request(1);
                return null;
            }
        };
        WebSocket ws = HttpClient.newHttpClient().newWebSocketBuilder()
                .buildAsync(URI.create("ws://localhost:" + port + "/feed?" + mode), listener)
                .join();
        done.await(5, TimeUnit.SECONDS);
        System.out.println("  client: received " + received + " of " + expected + " messages");
        ws.abort();
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(ConcurrentSends.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            System.out.println("plain session:");
            listen(port, "plain");
            System.out.println("decorated session:");
            listen(port, "safe");
        }
    }
}
Output
plain session:
  server: without ConcurrentWebSocketSessionDecorator, failed sends: 150
  first error: IllegalStateException: The remote endpoint was in state [TEXT_PARTIAL_WRITING] which is an invalid state for called method
  client: received 50 of 200 messages
decorated session:
  server: with ConcurrentWebSocketSessionDecorator, failed sends: 0
  client: received 200 of 200 messages
  • Without the decorator, sends failed with IllegalStateException: the remote endpoint was still busy writing another message when the next thread called sendMessage. In this run 150 of 200 sends failed and the client received 50. Because this is a race, the counts and the state named in the message can differ between runs and machines; in three runs here the counts were the same.
  • With the decorator, all 200 messages arrived. ConcurrentWebSocketSessionDecorator lets one thread send at a time and queues messages from the others, up to a time limit, here 10 seconds, and a buffer limit, here 64 MB.

The limits matter: a slow client fills the buffer, and when either limit is exceeded the decorator closes the session by default. That protects the server from running out of memory because of one slow consumer. Choose the limits from how much data a client may fall behind by. STOMP applications get this protection built in, since Spring wraps every STOMP session in the decorator, with limits set through configureWebSocketTransport.

STOMP: topics, controllers and a broker

With many rooms, private messages and server-side events, a raw handler turns into a home-made messaging system. STOMP over WebSocket replaces it with destinations and annotated methods. In this program, clients send to /app/rooms/{room}, a controller method processes the message, and the simple broker delivers the result to every subscriber of /topic/rooms/{room}:

Java
package demo.stomp;

import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.JacksonJsonMessageConverter;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompFrameHandler;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.messaging.WebSocketStompClient;

@SpringBootApplication
public class StompChat {

    public record ChatIn(String from, String text) {}

    public record ChatOut(String room, String from, String text) {}

    public record Notice(String text) {}

    @Configuration
    @EnableWebSocketMessageBroker
    static class BrokerConfig implements WebSocketMessageBrokerConfigurer {
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/ws");                       // the WebSocket URL
        }

        @Override
        public void configureMessageBroker(MessageBrokerRegistry registry) {
            registry.setApplicationDestinationPrefixes("/app"); // to @MessageMapping
            registry.enableSimpleBroker("/topic");              // in-memory broker
        }
    }

    @Controller
    static class ChatController {
        private final SimpMessagingTemplate messaging;

        ChatController(SimpMessagingTemplate messaging) {
            this.messaging = messaging;
        }

        // A client SENDs to /app/rooms/java; every subscriber of /topic/rooms/java gets it
        @MessageMapping("/rooms/{room}")
        @SendTo("/topic/rooms/{room}")
        public ChatOut say(@DestinationVariable String room, ChatIn in) {
            if (in.text().equals("!users")) {
                messaging.convertAndSend("/topic/notices",
                        new Notice("user list requested in " + room));
            }
            return new ChatOut(room, in.from(), in.text());
        }
    }

    static StompSession connect(int port, String name, BlockingQueue<String> screen)
            throws Exception {
        WebSocketStompClient client = new WebSocketStompClient(new StandardWebSocketClient());
        client.setMessageConverter(new JacksonJsonMessageConverter());
        StompSession session = client.connectAsync("ws://localhost:" + port + "/ws",
                new StompSessionHandlerAdapter() { }).get(5, TimeUnit.SECONDS);
        subscribe(session, "/topic/rooms/java", ChatOut.class, name, screen);
        subscribe(session, "/topic/notices", Notice.class, name, screen);
        return session;
    }

    static void subscribe(StompSession session, String destination, Class<?> type,
                          String name, BlockingQueue<String> screen) {
        session.subscribe(destination, new StompFrameHandler() {
            @Override
            public Type getPayloadType(StompHeaders headers) {
                return type;
            }

            @Override
            public void handleFrame(StompHeaders headers, Object payload) {
                screen.add(name + " got on " + headers.getDestination() + ": " + payload);
            }
        });
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(StompChat.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            BlockingQueue<String> anaScreen = new LinkedBlockingQueue<>();
            BlockingQueue<String> benScreen = new LinkedBlockingQueue<>();
            StompSession ana = connect(port, "ana", anaScreen);
            StompSession ben = connect(port, "ben", benScreen);
            Thread.sleep(300);                                  // let both SUBSCRIBEs arrive

            ana.send("/app/rooms/java", new ChatIn("ana", "records or classes?"));
            System.out.println(anaScreen.poll(5, TimeUnit.SECONDS));
            System.out.println(benScreen.poll(5, TimeUnit.SECONDS));

            ben.send("/app/rooms/java", new ChatIn("ben", "!users"));
            for (BlockingQueue<String> screen : List.of(anaScreen, benScreen)) {
                String a = screen.poll(5, TimeUnit.SECONDS);
                String b = screen.poll(5, TimeUnit.SECONDS);
                // the two topics are delivered independently; print them in a fixed order
                System.out.println(a.compareTo(b) < 0 ? a : b);
                System.out.println(a.compareTo(b) < 0 ? b : a);
            }
            ana.disconnect();
            ben.disconnect();
        }
    }
}
Output
ana got on /topic/rooms/java: ChatOut[room=java, from=ana, text=records or classes?]
ben got on /topic/rooms/java: ChatOut[room=java, from=ana, text=records or classes?]
ana got on /topic/notices: Notice[text=user list requested in java]
ana got on /topic/rooms/java: ChatOut[room=java, from=ben, text=!users]
ben got on /topic/notices: Notice[text=user list requested in java]
ben got on /topic/rooms/java: ChatOut[room=java, from=ben, text=!users]
  • Ana's message to /app/rooms/java reached the say method, because /app is the application destination prefix. @DestinationVariable extracted java from the destination, and the JSON payload became a ChatIn record.
  • The return value went to /topic/rooms/java, as @SendTo says, and the broker delivered it to both subscribers. The method knows nothing about sessions or connections.
  • Ben's !users also triggered SimpMessagingTemplate.convertAndSend to /topic/notices. Any bean can publish this way, for example a service that reacts to an order or a scheduled job.
  • The notice and the chat message travel on different destinations, which the broker delivers independently, so the program sorts each client's two lines before printing them.
  • Both clients use JacksonJsonMessageConverter, the Jackson 3 based converter of Spring Framework 7. A first version of this program sent the notice as a plain String: the server wrote it as text/plain, the clients' JSON-only converter could not read it, and the frames were silently dropped. Use records for payloads, or give clients a converter for every content type the server sends.

The simple broker keeps subscriptions in memory, inside one application instance. With several instances behind a load balancer, a message published on one instance would not reach clients connected to another. enableStompBrokerRelay replaces the simple broker with an external STOMP broker such as RabbitMQ or ActiveMQ, which all instances share. That needs a running broker and was not run here.

Running WebSocket in production

  • Proxies and load balancers: every hop must allow the Upgrade handshake and long-lived connections. Idle timeouts in proxies close quiet connections, so send heartbeats. STOMP defines them, with intervals negotiated in the CONNECT frame, and the simple broker sends them once it is given a TaskScheduler with setTaskScheduler.
  • Sticky routing is not enough: a connection stays on one instance, but events can start on any instance. Use a broker relay, or another shared channel, to publish across instances.
  • Fallbacks: registry.addEndpoint("/ws").withSockJS() adds SockJS, which falls back to HTTP streaming or polling where WebSocket is blocked. Clients then need the SockJS JavaScript library, and the URL scheme is http rather than ws.
  • Thread model: STOMP messages are processed on Spring's inbound channel thread pool, not on Tomcat request threads. Long work in a @MessageMapping method delays other messages; size the pool with configureClientInboundChannel, or hand the work off.
  • Message size: STOMP messages are limited to 64 KB by default, configured with setMessageSizeLimit in configureWebSocketTransport. For large data, send a link and fetch it over HTTP.
  • Testing: as these programs show, a test can start the application on a random port and connect real clients, which catches handshake, origin and serialization problems that unit tests miss.

Choosing an approach

WebSocket choices in Spring Boot
NeedUse
One stream of data per connection, simple protocolTextWebSocketHandler with @EnableWebSocket
Rooms, topics and many message typesSTOMP with @EnableWebSocketMessageBroker
Server events from any beanSimpMessagingTemplate.convertAndSend
Authentication of connectionsThe handshake: a HandshakeInterceptor or Spring Security
Protection from other websitessetAllowedOrigins or setAllowedOriginPatterns
Sending from several threadsConcurrentWebSocketSessionDecorator, built into STOMP
Several application instancesenableStompBrokerRelay with an external broker
Networks that block WebSocketwithSockJS()
One-way updates only, server to browserServer-sent events with SseEmitter, which is plain HTTP

When the browser only needs to receive updates, server-sent events are simpler than WebSocket and work through every HTTP proxy. For the HTTP side of an application, see Spring Boot @RestController, and for how browsers restrict cross-origin HTTP calls, see Spring Boot CORS.