Build Real‑Time Broadcast with Spring Boot 3 WebSocket in Minutes

This article walks through creating a real‑time broadcast system using Spring Boot 3 and WebSocket, covering Maven dependency setup, backend configuration, message controller implementation, and a simple front‑end page that connects via SockJS and STOMP to push notifications instantly.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Build Real‑Time Broadcast with Spring Boot 3 WebSocket in Minutes

Real‑time message push is essential for user experience in chat, e‑commerce, and finance, but traditional HTTP polling wastes resources and cannot guarantee immediacy.

WebSocket establishes a persistent bi‑directional channel, turning push from passive pulling into active broadcasting. The following steps show how to implement a simple real‑time broadcast with Spring Boot.

1. Add Dependency

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

Only this dependency is required; no extra configuration files are needed.

2. Enable WebSocket

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // broadcast prefix
        config.enableSimpleBroker("/topic");
        // client‑to‑server prefix
        config.setApplicationDestinationPrefixes("/app");
    }

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

The annotations activate STOMP‑based messaging, define "/topic" for broadcasting, and set "/app" as the client‑to‑server prefix. The endpoint "/ws" is the WebSocket entry point, with SockJS fallback for browsers that lack native support.

3. Define Message Controller

@Controller
public class NotifyController {

    @MessageMapping("/send")
    @SendTo("/topic/notify")
    public String send(String message) {
        return String.format("Broadcast message: %s", message);
    }
}

The method receives messages sent to "/app/send" and automatically broadcasts the formatted string to all clients subscribed to "/topic/notify".

4. Front‑end Page

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Real‑time Notification System</title>
  <script src="/libs/socket.min.js"></script>
  <script src="/libs/stomp.min.js"></script>
</head>
<body>
  <h2>Real‑time Notification System</h2>
  <div id="notifys"></div>
  <input type="text" id="message" placeholder="Enter message">
  <button onclick="sendMessage()">Send Message</button>

  <script>
    let client = null;
    function connect() {
      const socket = new SockJS('http://localhost:8080/ws');
      client = Stomp.over(socket);
      client.connect({}, frame => {
        client.subscribe('/topic/notify', msg => {
          showNotify(msg.body);
        });
      }, error => {
        console.error(`WebSocket connection error: ${error}`);
      });
    }

    function sendMessage() {
      const elt = document.querySelector('#message');
      const message = elt.value;
      if (client && client.connected) {
        client.send('/app/send', {}, message);
        elt.value = '';
      } else {
        console.error('WebSocket connection error.');
      }
    }

    function showNotify(message) {
      const notifys = document.querySelector('#notifys');
      const p = document.createElement('p');
      p.textContent = message;
      notifys.appendChild(p);
    }

    connect();
  </script>
</body>
</html>

The page loads SockJS and STOMP libraries, connects to the "/ws" endpoint, subscribes to "/topic/notify", and provides an input box to send messages.

5. Test

Open the page, type a message, and click “Send Message”. All connected browsers will instantly display the broadcasted text.

WebSocket demo screenshot
WebSocket demo screenshot
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-TimeWebSocketstompspring-bootsockjs
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
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.