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 GETUpgrade: websocket101 Switching Protocols
Spring offers two levels of support, both in Spring Framework 7.0 and enabled in Spring Boot by spring-boot-starter-websocket
| Model | You write | Best for |
|---|---|---|
Raw WebSocket, @EnableWebSocket | A WebSocketHandler | Simple protocols, streaming data, one handler per endpoint |
STOMP messaging, @EnableWebSocketMessageBroker | @MessageMapping/topic/prices | Chat, notifications, publish and subscribe with many topics |
SockJS fallback, withSockJS() | Nothing extra on the server | Browsers 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 CONNECTSUBSCRIBESENDjava.net.http.WebSocketWebSocketStompClient
A first WebSocket handler
An echo server is the smallest complete exchange: open, send, receive, close. The handler extends TextWebSocketHandlerbye
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));
}
}
}
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
ran once theafterConnectionEstablished handshake had completed, with the path101 ./echo - Each text message reached
, andhandleTextMessage sent the reply on the same connection. Nothing in this code mentions requests or responses: the server could equally send without being asked.session.sendMessage - After
, the server calledbye . The client received close code 1000 with the reason, and the server'ssession.close(CloseStatus.NORMAL.withReason("see you")) reported the same status.afterConnectionClosed
@EnableWebSocketWebSocketConfigurerWebSocketSessiongetAttributes()
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:
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));
}
}
}
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
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 readHandshakeInterceptor from there to label each message.user - Eve's unknown token made
set 401 and returnbeforeHandshake , so the upgrade never happened and the client sawfalse instead of an open connection.HTTP 401 - A connection with a valid token but
was refused with 403 by the origin check ofOrigin: https://evil.example.net . Browsers always sendsetAllowedOrigins 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.Origin - The connection without any
header was accepted. Spring treats a missing origin as a non-browser client, which the token must then authenticate.Origin - 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 synchronizedConcurrentWebSocketSessionDecorator
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");
}
}
}
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
: the remote endpoint was still busy writing another message when the next thread calledIllegalStateException . 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.sendMessage - With the decorator, all 200 messages arrived.
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.ConcurrentWebSocketSessionDecorator
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}/topic/rooms/{room}
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();
}
}
}
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
reached the/app/rooms/java method, becausesay is the application destination prefix./app extracted@DestinationVariable from the destination, and the JSON payload became ajava record.ChatIn - The return value went to
, as/topic/rooms/java says, and the broker delivered it to both subscribers. The method knows nothing about sessions or connections.@SendTo - Ben's
also triggered!users toSimpMessagingTemplate.convertAndSend . Any bean can publish this way, for example a service that reacts to an order or a scheduled job./topic/notices - 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
, the Jackson 3 based converter of Spring Framework 7. A first version of this program sent the notice as a plainJacksonJsonMessageConverter : the server wrote it asString , 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.text/plain
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
Running WebSocket in production
- Proxies and load balancers: every hop must allow the
handshake and long-lived connections. Idle timeouts in proxies close quiet connections, so send heartbeats. STOMP defines them, with intervals negotiated in theUpgrade frame, and the simple broker sends them once it is given aCONNECT withTaskScheduler .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:
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 isregistry.addEndpoint("/ws").withSockJS() rather thanhttp .ws - Thread model: STOMP messages are processed on Spring's inbound channel thread pool, not on Tomcat request threads. Long work in a
method delays other messages; size the pool with@MessageMapping , or hand the work off.configureClientInboundChannel - Message size: STOMP messages are limited to 64 KB by default, configured with
insetMessageSizeLimit . For large data, send a link and fetch it over HTTP.configureWebSocketTransport - 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
| Need | Use |
|---|---|
| One stream of data per connection, simple protocol | TextWebSocketHandler@EnableWebSocket |
| Rooms, topics and many message types | STOMP with @EnableWebSocketMessageBroker |
| Server events from any bean | SimpMessagingTemplate.convertAndSend |
| Authentication of connections | The handshake: a HandshakeInterceptor |
| Protection from other websites | setAllowedOriginssetAllowedOriginPatterns |
| Sending from several threads | ConcurrentWebSocketSessionDecorator |
| Several application instances | enableStompBrokerRelay |
| Networks that block WebSocket | withSockJS() |
| One-way updates only, server to browser | Server-sent events with SseEmitter |
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