Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 119 ยท Spring Boot

WebSockets with Jakarta and Spring

Learn how the WebSocket handshake and frames work, then build real-time features with Jakarta endpoints, Spring handlers and STOMP messaging over a broker.

HTTP is a request-and-response protocol: the client asks, the server answers, and the conversation ends. That is a poor fit for a chat window, a live dashboard or a multiplayer game, where the server needs to push data the moment something happens. You could poll the server every second, but that wastes bandwidth and still feels laggy.

A WebSocket solves this by upgrading one HTTP connection into a long-lived, two-way channel. Both sides can send messages at any time, with only a few bytes of overhead each. In this lesson you will look inside the protocol (handshake and frames), run a tiny real WebSocket server in plain Java, and then see how Jakarta WebSocket, Spring's WebSocketHandler and Spring's STOMP messaging support wrap the same ideas. You should know Spring MVC and the basics of HTTP.

From HTTP to WebSocket: the handshake

A WebSocket connection starts as an ordinary HTTP/1.1 GET request with special headers. If the server agrees, it answers 101 Switching Protocols, and from then on the same TCP connection carries WebSocket frames instead of HTTP.

sequenceDiagram
  participant B as Browser
  participant S as Server
  B->>S: GET /chat (Upgrade: websocket, Sec-WebSocket-Key: abc...)
  S-->>B: 101 Switching Protocols (Sec-WebSocket-Accept: xyz...)
  Note over B,S: Same TCP connection, now WebSocket frames
  B->>S: text frame "hello"
  S->>B: text frame "hi, hello"
  S->>B: text frame (pushed, nobody asked)
  B->>S: close frame
  S-->>B: close frame

The handshake is plain HTTP; after the 101 response both sides may send frames at any time.

The client sends a random Sec-WebSocket-Key. The server proves it understood the protocol by hashing that key together with a fixed GUID from the specification (RFC 6455), and returning the result as Sec-WebSocket-Accept. This stops a normal HTTP server (or a confused cache) from accidentally "accepting" an upgrade.

After the handshake, data travels in frames. A frame has an opcode (text, binary, ping, pong, close), a payload length and the payload. One rule is easy to forget: frames sent from the client to the server are masked with a random 4-byte key (to protect proxies from cache-poisoning tricks), while frames from the server are not. The next example computes the accept value from the RFC's own sample key and builds the masked frame for the text Hello:

Java The accept key and a masked text frame

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The server's frame is just 81 05 followed by the five plain bytes: two bytes of overhead. You never write this by hand in real projects, but knowing it explains why WebSockets are cheap and why proxies and load balancers must be configured to keep such connections open for a long time.

A tiny WebSocket server in plain Java

The JDK ships a WebSocket client (java.net.http.WebSocket) but no server. To see the whole protocol work, the next example implements a minimal server on a ServerSocket: it reads the handshake, answers with the accept key, then reads masked frames and broadcasts each message to every connected user. The user name comes from the URL path (/chat/alice), like a path parameter. Two JDK clients connect to it over loopback:

Java A chat server and two real WebSocket clients

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice how little this server does: no routing, no authentication, no ping/pong, no fragmented messages. A production server also handles ping/pong heartbeats (to detect dead connections behind proxies), fragmentation (one message split across frames), size limits and backpressure. That is why you use a library.

Jakarta WebSocket endpoints

Jakarta WebSocket (formerly javax.websocket, part of Jakarta EE) is the standard Java API. You annotate a class and the container calls its methods for each event. The in the path is a path parameter, just like the one our toy server parsed:

Java
@ServerEndpoint("/ws/chat/{user}")
@Component
public class ChatEndpoint {

    private static final Map<String, Session> SESSIONS = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("user") String user) {
        SESSIONS.put(user, session);
    }

    @OnMessage
    public void onMessage(String text, @PathParam("user") String user) {
        SESSIONS.values().forEach(s -> s.getAsyncRemote().sendText(user + ": " + text));
    }

    @OnClose
    public void onClose(@PathParam("user") String user) {
        SESSIONS.remove(user);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        // log it; the container closes the connection afterwards
    }
}

In a Spring Boot application this endpoint needs a ServerEndpointExporter bean to register @ServerEndpoint classes, and one catch: instances are created by the WebSocket container for each connection, so dependency injection into them is awkward. Use static state, as above, or inject carefully. For this reason many Spring teams prefer Spring's own API.

Spring's WebSocketHandler

Add spring-boot-starter-websocket. A handler is an ordinary Spring bean, with no per-connection instances:

Java
@Component
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 session, TextMessage message) throws IOException {
        for (WebSocketSession peer : sessions) {
            peer.sendMessage(new TextMessage(session.getPrincipal().getName() + ": " + message.getPayload()));
        }
    }

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

@Configuration
@EnableWebSocket
class WebSocketConfig implements WebSocketConfigurer {

    private final ChatHandler chatHandler;

    WebSocketConfig(ChatHandler chatHandler) { this.chatHandler = chatHandler; }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(chatHandler, "/ws/chat")
                .setAllowedOriginPatterns("https://app.example.com");
    }
}

A WebSocketSession is not safe to write to from several threads at once. In the handler above two threads may call sendMessage on the same peer simultaneously and corrupt the stream. Wrap sessions in ConcurrentWebSocketSessionDecorator, or use STOMP, which serializes sends for you.

Always restrict allowed origins. Browsers send cookies with a WebSocket handshake to any site, and the same-origin policy does not apply to WebSockets, so a malicious page could open a connection as the logged-in user. This is called cross-site WebSocket hijacking; see Web Security Basics for the CSRF family.

STOMP: messaging on top of WebSocket

A raw WebSocket carries bytes or text with no meaning attached. You would have to invent your own conventions for "which room", "subscribe me to this topic", or "who is this for". STOMP (Simple Text Oriented Messaging Protocol) is a small text protocol that adds exactly that: frames such as CONNECT, SUBSCRIBE, SEND and MESSAGE, with headers like destination. Spring supports it directly.

flowchart LR
  C1["Browser A<br/>SEND /app/chat"] --> IN["Inbound channel"]
  IN -->|"/app/..."| H["@MessageMapping<br/>controller method"]
  H -->|"@SendTo /topic/chat"| B["Message broker"]
  IN -->|"/topic/..."| B
  B --> C2["Browser A<br/>subscribed to /topic/chat"]
  B --> C3["Browser B<br/>subscribed to /topic/chat"]

Messages sent to /app/... reach your controller; messages sent to /topic/... are fanned out by the broker to all subscribers.

The following example is a deliberately small STOMP broker in plain Java. It parses real STOMP frames, tracks subscriptions, and delivers SEND frames to every subscriber of the destination as MESSAGE frames:

Java A mini STOMP broker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The real Spring broker also handles acknowledgements, heartbeats, transactions and per-user destinations, but the structure is the same: a table from destinations to subscriptions.

Spring STOMP configuration

Java
@Configuration
@EnableWebSocketMessageBroker
class StompConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").setAllowedOriginPatterns("https://app.example.com");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");   // routed to @MessageMapping methods
        registry.enableSimpleBroker("/topic", "/queue");      // in-memory broker for the rest
    }
}

record ChatMessage(String from, String text) {}

@Controller
class ChatController {

    private final SimpMessagingTemplate messaging;

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

    @MessageMapping("/chat")                 // client sends to /app/chat
    @SendTo("/topic/chat")                   // the return value goes to every subscriber
    ChatMessage chat(ChatMessage incoming, Principal user) {
        return new ChatMessage(user.getName(), incoming.text());
    }

    @MessageMapping("/private")
    void direct(PrivateMessage message, Principal user) {
        messaging.convertAndSendToUser(message.to(), "/queue/inbox", message.text());
    }
}

The method parameters are resolved much like in REST controllers: the payload is converted from JSON by Jackson. convertAndSendToUser delivers to one user's /user/queue/inbox. Any other service can also inject SimpMessagingTemplate and push events, for example when a scheduled job finishes. A browser client with the @stomp/stompjs library connects with new Client({ brokerURL: "wss://host/ws" }), then subscribe("/topic/chat", ...) and publish({ destination: "/app/chat", body: ... }).

Production concerns

  • Security. Authenticate during the handshake (cookie or token) and authorize each SUBSCRIBE/SEND with a ChannelInterceptor or Spring Security message rules. Never trust a from field sent by the client.
  • Scaling. The simple broker lives in one JVM, so subscribers on another instance never see the message. For several instances use enableStompBrokerRelay with RabbitMQ, or a shared bus such as Redis pub/sub.
  • Proxies. Load balancers need Upgrade support and idle timeouts longer than your heartbeat interval.
  • Limits. Set maximum message size and buffer limits; one slow client must not exhaust memory.
  • Fallbacks. If you only push events from server to browser, Server-Sent Events are simpler. Use WebSockets when the client also sends frequently.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the server answer to a successful WebSocket handshake request?

    The handshake is an HTTP upgrade. After 101 the connection carries WebSocket frames, and the accept header proves the server understood the protocol.
  2. 2. In a WebSocket connection, which frames are masked?

    Clients must mask frames with a random 4-byte key, while server frames are sent unmasked.
  3. 3. Why must you configure allowed origins for a WebSocket endpoint?

    Cross-site WebSocket hijacking works because the browser sends cookies with the handshake from any page. Checking the Origin header prevents it.
  4. 4. In the Spring STOMP configuration above, a client sends to /app/chat. Where does the message go first?

    Destinations with the application prefix are routed to controller methods. Other destinations go to the broker.
  5. 5. Why does the built-in simple broker not work behind several application instances?

    Use a broker relay (for example RabbitMQ) or another shared channel so every instance sees every message.

Summary

  • A WebSocket starts as an HTTP upgrade (101 Switching Protocols) and then carries masked client frames and unmasked server frames over one connection.
  • Jakarta WebSocket uses @ServerEndpoint, @OnOpen, @OnMessage, @OnClose; Spring's TextWebSocketHandler gives you singleton beans, but sessions need thread-safe writes.
  • STOMP adds destinations, subscriptions and framing; Spring maps /app/... to @MessageMapping methods and fans out /topic/... through a broker.
  • Restrict origins, authenticate the handshake, authorize messages, and plan for several instances with a broker relay.

Next: GraphQL with Spring shows another way to give clients real-time and flexible data access.