0
0
SpringbootHow-ToBeginner · 4 min read

How to Create a Chat App with Spring Boot and WebSocket

To create a chat app in Spring Boot, use Spring WebSocket for real-time messaging and STOMP protocol for communication. Define a WebSocket configuration, create message handling controllers, and use a simple frontend to send and receive chat messages.
📐

Syntax

This is the basic setup for a Spring Boot chat app using WebSocket and STOMP:

  • @EnableWebSocketMessageBroker: Enables WebSocket message handling.
  • configureMessageBroker(): Sets up message broker for routing messages.
  • registerStompEndpoints(): Registers the WebSocket endpoint clients connect to.
  • @MessageMapping: Maps incoming messages to controller methods.
  • @SendTo: Sends messages to subscribed clients.
java
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat-websocket").withSockJS();
    }
}
💻

Example

This example shows a simple Spring Boot chat app backend with WebSocket and a minimal frontend using SockJS and STOMP.js to send and receive messages in real-time.

java,html
/* WebSocketConfig.java */
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat-websocket").withSockJS();
    }
}

/* ChatMessage.java */
public class ChatMessage {
    private String from;
    private String text;

    public ChatMessage() {}

    public ChatMessage(String from, String text) {
        this.from = from;
        this.text = text;
    }

    public String getFrom() { return from; }
    public void setFrom(String from) { this.from = from; }

    public String getText() { return text; }
    public void setText(String text) { this.text = text; }
}

/* ChatController.java */
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class ChatController {
    @MessageMapping("/sendMessage")
    @SendTo("/topic/messages")
    public ChatMessage sendMessage(ChatMessage message) {
        return message; // simply broadcast the received message
    }
}

/* index.html (frontend) */
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Spring Boot Chat App</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
</head>
<body>
    <h2>Chat App</h2>
    <input id="from" placeholder="Your name" /> <br />
    <input id="text" placeholder="Message" />
    <button onclick="sendMessage()">Send</button>
    <ul id="messages"></ul>

    <script>
        let stompClient = null;

        function connect() {
            const socket = new SockJS('/chat-websocket');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function () {
                stompClient.subscribe('/topic/messages', function (msg) {
                    showMessage(JSON.parse(msg.body));
                });
            });
        }

        function sendMessage() {
            const from = document.getElementById('from').value;
            const text = document.getElementById('text').value;
            if(from && text) {
                stompClient.send('/app/sendMessage', {}, JSON.stringify({from: from, text: text}));
                document.getElementById('text').value = '';
            }
        }

        function showMessage(message) {
            const messages = document.getElementById('messages');
            const li = document.createElement('li');
            li.appendChild(document.createTextNode(message.from + ': ' + message.text));
            messages.appendChild(li);
        }

        connect();
    </script>
</body>
</html>
Output
A web page with a chat input and a list showing messages from users in real-time as they send them.
⚠️

Common Pitfalls

Common mistakes when creating a Spring Boot chat app include:

  • Not enabling @EnableWebSocketMessageBroker, so WebSocket messaging won't work.
  • Forgetting to register the STOMP endpoint with SockJS fallback, causing connection failures in some browsers.
  • Using incorrect destination prefixes in client and server, leading to messages not being routed.
  • Not handling CORS properly if frontend and backend run on different origins.
java
/* Wrong: Missing @EnableWebSocketMessageBroker */
@Configuration
public class WrongConfig implements WebSocketMessageBrokerConfigurer {
    // This will not enable WebSocket message handling
}

/* Right: Include @EnableWebSocketMessageBroker */
@Configuration
@EnableWebSocketMessageBroker
public class CorrectConfig implements WebSocketMessageBrokerConfigurer {
    // Proper WebSocket setup
}
📊

Quick Reference

Spring Boot Chat App Key Points:

  • Use @EnableWebSocketMessageBroker to enable WebSocket support.
  • Configure message broker with enableSimpleBroker and setApplicationDestinationPrefixes.
  • Register STOMP endpoint with SockJS fallback for browser compatibility.
  • Use @MessageMapping for incoming messages and @SendTo to broadcast.
  • Frontend uses SockJS and STOMP.js to connect and send/receive messages.

Key Takeaways

Enable WebSocket messaging with @EnableWebSocketMessageBroker in Spring Boot.
Register a STOMP endpoint with SockJS fallback for reliable client connections.
Use @MessageMapping and @SendTo to handle and broadcast chat messages.
Frontend connects via SockJS and STOMP.js to send and receive messages in real-time.
Check destination prefixes and CORS settings to avoid common connection issues.