Backend Development 10 min read

Implementing a WebSocket Chat Application with Spring Boot

This tutorial explains the advantages of WebSocket over HTTP and provides a step‑by‑step guide, including Maven dependency, Spring Boot configuration, a ServerEndpoint class, a simple HTML/JavaScript front‑end, and a controller method, to build a real‑time chat system with online/offline notifications and private or broadcast messaging.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Implementing a WebSocket Chat Application with Spring Boot

WebSocket enables full‑duplex communication between client and server, allowing messages to be pushed at any time after a single handshake, unlike the request‑response model of HTTP.

The article first explains several advantages of WebSocket over HTTP, such as persistent connections, reduced header overhead, higher concurrency, and lower resource consumption.

It then provides a step‑by‑step guide to build a simple chat system with Spring Boot:

1. Add the <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> to the Maven pom.

2. Create a configuration class that registers a ServerEndpointExporter bean:

@Configuration
public class WebSocketStompConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3. Implement a @ServerEndpoint("/websocket/{username}") class that manages online users, handles @OnOpen, @OnMessage, @OnClose, and @OnError events, and broadcasts or routes messages:

@Component
@ServerEndpoint("/websocket/{username}")
public class WebSocket {
    private static int onlineNumber = 0;
    private static Map
clients = new ConcurrentHashMap<>();
    private Session session;
    private String username;
    // @OnOpen, @OnMessage, @OnClose, @OnError implementations ...
    // sendMessageAll, sendMessageTo, getOnlineCount methods
}

4. Write a minimal HTML/JavaScript front‑end that opens a WebSocket connection, displays online users, and sends/receives chat messages using JSON:

<!DOCTYPE html>
<html>
<head>
    <title>websocket</title>
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
    <script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
</head>
<body>
    ... (HTML UI elements) ...
    <script type="text/javascript">
        var webSocket;
        if ("WebSocket" in window) {
            webSocket = new WebSocket("ws://localhost:9030/websocket/" + document.getElementById('username').value);
            webSocket.onopen = function() { console.log("已经连通了websocket"); };
            webSocket.onmessage = function(evt) { /* handle incoming JSON messages */ };
            webSocket.onclose = function() { console.log("连接已关闭..."); };
        } else {
            alert("您的浏览器不支持 WebSocket!");
        }
        function send() { /* send message JSON */ }
        function closeWebSocket() { webSocket.close(); }
    </script>
</body>
</html>

5. Add a Spring MVC controller method to forward the username to the HTML page:

@RequestMapping("/websocket/{name}")
public String webSocket(@PathVariable String name, Model model) {
    try {
        logger.info("跳转到websocket的页面上");
        model.addAttribute("username", name);
        return "websocket";
    } catch (Exception e) {
        logger.info("跳转到websocket的页面上发生异常,异常信息是:" + e.getMessage());
        return "error";
    }
}

Running the application provides online/offline notifications, one‑to‑one chat, and broadcast messaging, demonstrating a complete real‑time communication solution.

JavaBackend DevelopmentSpring BootWebSocketReal-time CommunicationChat Application
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login 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.