DEV Community

Cover image for Understanding WebSockets in Spring Boot: A Beginner-Friendly Guide
Gihan Benaragama
Gihan Benaragama

Posted on

Understanding WebSockets in Spring Boot: A Beginner-Friendly Guide

Introduction

When building web applications, we often need to communicate between the frontend and backend.

For example, imagine you are using a messaging application. When someone sends you a message, you expect to receive it immediately without refreshing the page.

But how does that happen?

Spring Boot provides excellent support for WebSocket communication through Spring WebSocket and Spring Messaging.

In this article, we will explore:

  • What WebSockets are
  • Why WebSockets are useful
  • How WebSockets work
  • What STOMP is and why we use it
  • WebSockets in Spring Boot
  • WebSocket security
  • Real-world use cases
  • Important things to consider when developing WebSocket applications

Let's get started!


1. What is a WebSocket?

A WebSocket is a communication protocol that allows a client and server to communicate with each other through a single, long-lived connection.

Unlike traditional HTTP communication, WebSockets support two-way communication.

This means:

  • The client can send messages to the server.
  • The server can send messages to the client.
  • Both can communicate without repeatedly creating new HTTP requests.

For example, consider a normal HTTP application:

  1. The frontend sends a request to the backend.
  2. The backend processes the request.
  3. The backend sends a response.
  4. The connection is no longer used for that request.

With WebSockets, the connection stays open, allowing both sides to exchange messages whenever necessary.

HTTP vs WebSocket

HTTP WebSocket
Request-response communication Two-way communication
Usually a separate request for each operation Persistent connection
Client normally initiates requests Both client and server can send messages
Suitable for regular API operations Suitable for real-time communication

Important: WebSockets do not replace HTTP. Both technologies are useful for different purposes.


simple

2. How Does WebSocket Communication Work?

WebSocket communication starts with an HTTP request called a WebSocket handshake.

The basic process is:

  1. The client requests a WebSocket connection.
  2. The server accepts the connection and upgrades it from HTTP to WebSocket.
  3. A persistent connection is established.
  4. Both client and server can exchange messages.
  5. The connection remains open until it is closed.

For example:

Imagine a student using a university Lost & Found application.

  • A student submits a claim for a lost item.
  • An administrator approves the claim.
  • The backend sends a notification through WebSocket.
  • The student immediately receives the notification.

There is no need to refresh the page or repeatedly request the server to check for updates.


3. What is STOMP and Why Do We Use It?

When working with WebSockets in Spring Boot, you will often encounter something called STOMP.

STOMP stands for Simple Text Oriented Messaging Protocol.

It is a messaging protocol that works over WebSocket and provides a structured way to exchange messages.

But why do we need it?

WebSocket itself provides the communication connection. However, it does not define an application-level messaging structure or destination system.

STOMP helps solve this problem.

It provides features such as:

  • Sending messages to specific destinations.
  • Subscribing to destinations.
  • Publishing messages.
  • Routing messages between clients and the server.

Example

Suppose a user wants to receive notifications.

The frontend subscribes to:

/user/queue/notifications
Enter fullscreen mode Exit fullscreen mode

When the backend sends a notification to that user, the message broker routes it to the subscribed destination.

This makes message communication easier to organize and manage.

Remember:

  • WebSocket: Provides the communication connection.
  • STOMP: Defines how messages are exchanged and routed.
  • Spring Messaging: Handles messaging operations inside the application.

concepts

4. WebSocket Architecture in Spring Boot

Spring Boot provides WebSocket support through the spring-boot-starter-websocket dependency.

The main components include:

1. WebSocket Configuration

This is where we configure WebSocket endpoints, message brokers, and destination prefixes.

For example:

  • /ws – WebSocket connection endpoint.
  • /topic – Common destinations for messages published to multiple subscribers.
  • /queue – Destinations commonly used for individual or point-to-point messages.
  • /app – Prefix for messages sent from clients to application-level message handlers.
  • /user – Prefix used for user-specific destinations.

2. Message Broker

A message broker manages message routing between publishers and subscribers.

Spring provides a simple in-memory message broker that is suitable for smaller applications and development.

For larger applications, external brokers such as RabbitMQ can be integrated.

3. Controller

A WebSocket controller handles incoming messages from clients.

In Spring Boot, we can use @MessageMapping to define destinations that handle incoming STOMP messages.

4. Service Layer

The service layer contains the application's business logic.

For example, when an administrator approves a claim, the service can create a notification and send it to the appropriate user.

5. Frontend

The frontend connects to the WebSocket endpoint, subscribes to destinations, and receives messages.

For React applications, libraries such as @stomp/stompjs can be used for STOMP communication.


architecure

5. How to Implement WebSockets in Spring Boot

Let's look at a simple implementation.

Step 1: Add the Dependency

Add the following dependency to your Spring Boot project:

Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

This provides Spring's WebSocket and messaging support.

Step 2: Create WebSocket Configuration

Create a configuration class:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig
        implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(
            MessageBrokerRegistry config) {

        config.enableSimpleBroker("/topic", "/queue");

        config.setApplicationDestinationPrefixes("/app");

        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(
            StompEndpointRegistry registry) {

        registry.addEndpoint("/ws")
                .setAllowedOrigins("http://localhost:5173");
    }
}
Enter fullscreen mode Exit fullscreen mode

Let's understand the important annotations and methods.

  • @Configuration tells Spring that this class contains configuration.
  • @EnableWebSocketMessageBroker enables WebSocket messaging support.
  • enableSimpleBroker() enables Spring's built-in message broker.
  • setApplicationDestinationPrefixes() defines the prefix for application message destinations.
  • registerStompEndpoints() registers the endpoint used by clients to establish WebSocket connections.

Step 3: Create a Message Controller

We can use @MessageMapping to receive messages from clients.

@Controller
public class ChatController {

    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public String sendMessage(String message) {

        return message;
    }
}
Enter fullscreen mode Exit fullscreen mode

Here:

  • @MessageMapping("/chat") receives messages sent to /app/chat.
  • @SendTo("/topic/messages") broadcasts the returned message to subscribers of that destination.

Step 4: Connect from the Frontend

The frontend can connect using a STOMP client.

For React, install:

npm install @stomp/stompjs
Enter fullscreen mode Exit fullscreen mode

Example:

import { Client } from "@stomp/stompjs";

const client = new Client({
    brokerURL: "ws://localhost:8080/ws",

    onConnect: () => {

        client.subscribe("/topic/messages", (message) => {

            console.log(message.body);

        });

        client.publish({
            destination: "/app/chat",
            body: "Hello from React!"
        });
    }
});

client.activate();
Enter fullscreen mode Exit fullscreen mode

This is a simple example of sending and receiving messages using Spring Boot WebSockets and STOMP.

For production applications, you should also handle connection errors, reconnection, authentication, and authorization.


6. WebSocket Security in Spring Boot

Security is one of the most important topics when developing WebSocket applications.

Just because a user has established a WebSocket connection does not mean they should be allowed to access every message destination.

For example, imagine a university application where:

  • Students should receive their own notifications.
  • Administrators can manage claims.
  • Students should not receive another student's private messages.

We need proper authentication and authorization.

6.1 Authentication

Authentication answers the question:

Who is the user?

In Spring Security, authentication is generally established during the initial HTTP WebSocket handshake.

For example, if your application uses JWT authentication, you need to make sure the JWT is validated and the authenticated user identity is associated with the WebSocket session.

An important point: WebSocket connections do not automatically reuse a JWT sent in an ordinary REST API request.

With browser-based STOMP clients, a JWT can be sent in STOMP CONNECT headers. In that case, you need to implement a server-side STOMP ChannelInterceptor to validate the token and establish the authenticated user.

6.2 Authorization

Authorization answers the question:

What is the user allowed to do?

For example:

  • Students can subscribe to their own notifications.
  • Administrators can access administrator-specific messaging destinations.
  • Users cannot subscribe to another user's private notification destination.

Spring Security supports WebSocket message authorization.

You can configure authorization rules to restrict access to specific message destinations.

6.3 Protecting Private Messages

Consider this destination:

/user/queue/notifications
Enter fullscreen mode Exit fullscreen mode

This destination is commonly used to deliver notifications to individual authenticated users.

In Spring Boot, we can send a message using SimpMessagingTemplate:

messagingTemplate.convertAndSendToUser(
    username,
    "/queue/notifications",
    notification
);
Enter fullscreen mode Exit fullscreen mode

The frontend subscribes to:

/user/queue/notifications
Enter fullscreen mode Exit fullscreen mode

Spring resolves the user destination and routes the message to the appropriate authenticated user's session.

However, using /user does not automatically guarantee security. You must also configure authentication, authorization, and destination access correctly.


7. Real-World Uses of WebSockets

WebSockets are useful whenever applications need real-time communication.

Here are some common examples.

1. Real-Time Notifications

Applications can immediately notify users about important events.

Examples:

  • Claim approval notifications.
  • Order status updates.
  • New friend requests.
  • Payment status notifications.

2. Chat Applications

Messaging applications use WebSockets to exchange messages in real time.

Examples:

  • Private messaging.
  • Group chats.
  • Customer support chat.

3. Live Tracking Systems

WebSockets can deliver frequent location or status updates.

Examples:

  • Delivery tracking.
  • Vehicle tracking.
  • Live logistics monitoring.

4. Collaborative Applications

Multiple users can work on the same information simultaneously.

Examples:

  • Collaborative document editing.
  • Shared project boards.
  • Live dashboards.

5. Online Gaming

WebSockets can exchange real-time game events between players and servers.

They are useful for multiplayer games that need frequent communication.


8. WebSocket vs Polling

Before WebSockets became widely used, applications often used polling to check for updates.

Polling means the client repeatedly sends HTTP requests to ask the server whether new information is available.

For example:

  • Send a request every 5 seconds.
  • Check whether a new notification exists.
  • Repeat the process.

This can create unnecessary requests, especially when there are no updates.

WebSockets solve this by allowing the server to push messages to connected clients whenever new information is available.

However, polling is not always bad. For applications that do not need immediate updates, regular HTTP requests or polling may be simpler and sufficient.


9. Important Things to Consider When Using WebSockets

Although WebSockets are powerful, there are a few important things to remember.

1. Connection Management

WebSocket connections remain open, so applications must handle disconnections, reconnections, and inactive sessions.

2. Security

Always authenticate users and authorize access to message destinations. Never trust a username supplied by the client when sending private messages.

3. Scalability

Spring's simple in-memory message broker is suitable for smaller applications, but it may not be sufficient for large-scale systems.

External message brokers can help distribute messages across multiple application instances.

4. Offline Users

A WebSocket connection only delivers messages while a suitable connection is available.

If a user is offline, important notifications should be stored in a database so they can retrieve them later.

5. Message Validation

Always validate incoming messages. Do not blindly trust data received from clients.


Conclusion

WebSockets are an important technology for building modern real-time applications.

Spring Boot makes WebSocket implementation easier through Spring WebSocket and Spring Messaging.

By combining WebSocket, STOMP, and Spring Security, developers can build applications that support real-time communication while protecting private information.

Whether you are building a chat application, notification system, live dashboard, or tracking application, understanding WebSockets can be a valuable skill for a backend developer.

If you are learning Spring Boot, I recommend trying a small real-time notification feature in one of your projects. It is a great way to understand how WebSocket communication works in practice.

Happy Coding! 🚀

Top comments (0)