Skip to main content

Command Palette

Search for a command to run...

Building Real-Time Applications with Spring Websockets

Updated
3 min read
Building Real-Time Applications with Spring Websockets
A

I'm a seasoned Software Engineer with over half a decade of experience shaping the world of software development. My passion is anchored in writing code that is not just efficient, but also elegant and clean. An advocate for continuous improvement, I am forever on the hunt for the most cutting-edge developments in our dynamic industry.

Real-time functionality has become a necessity in the modern web, with users expecting instant updates in chat applications, live web page updates, or real-time tracking. Websockets are a technology that enables this, and in this post, we will dive into using Spring Websockets for building real-time applications.

What are Websockets?

Websockets provide a full-duplex communication channel over a single socket connection. Unlike traditional HTTP requests, which are unidirectional and require a new connection for each request, Websockets allow for bidirectional communication between the client and server. This means that the server can push updates to the client as they happen, without the client needing to request updates.

Spring Websockets

Spring Websockets is a module in the Spring Framework that provides support for Websockets. It provides an easy-to-use API for creating Websocket endpoints and handling Websocket events.

Building a Chat Application with Spring Websockets

Let's dive into a practical example and build a simple chat application using Spring Websockets.

Configuring Websockets

Next, we need to configure the Websocket endpoint and message broker. Create a configuration class and annotate it with @Configuration and @EnableWebSocketMessageBroker.

@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").withSockJS();
    }
}

Creating the Message Model

Our chat messages will be simple, containing a name and content. Create a Message class to represent this:

public record Message(String name, String content) {}

Creating the Message Controller

Now, let's create a MessageController to handle sending and receiving messages:

@Controller
public class MessageController {

    @MessageMapping("/chat.sendMessage")
    @SendTo("/topic/public")
    public Message sendMessage(@Payload Message message) {
        return message;
    }
}

Creating a simple client

Finally, we need to create the client. We'll use SockJS and STOMP for the client-side Websocket handling. Here's a simple HTML page with some JavaScript to handle the chat:

<!DOCTYPE html>
<html>
<head>
    <title>Chat</title>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
```html
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script>
        var stompClient = null;
        function connect() {
            var socket = new SockJS('/chat');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                stompClient.subscribe('/topic/public', function (message) {
                    showMessage(JSON.parse(message.body).content);
                });
            });
        }
        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
            }
        }
        function sendMessage() {
            var message = document.getElementById('message').value;
            stompClient.send("/app/chat.sendMessage", {}, JSON.stringify({'content': message}));
        }
        function showMessage(message) {
            var messageElement = document.createElement('li');
            messageElement.appendChild(document.createTextNode(message));
            document.getElementById('messageList').appendChild(messageElement);
        }
    </script>
</head>
<body onload="connect();">
    <ul id="messageList"></ul>
    <input type="text" id="message" />
    <button onclick="sendMessage();">Send</button>
    <button onclick="disconnect();">Disconnect</button>
</body>
</html>

Conclusion

In this post, we've seen how to use Spring Websockets to build a real-time chat application. The same principles can be applied to build other types of real-time applications, such as live updates in a web application. With Spring Websockets, building real-time applications is straightforward and efficient.

More from this blog

A

Adrian Kodja some Insights and Innovations: Exploring the World of a Seasoned Software Engineer

35 posts

I am a software craftsman with a passion for writing clean, efficient, and well-organized code.