Implementing WebSockets in Spring Boot: Real-Time Communication

WebSockets provide a full-duplex communication channel over a single TCP connection, allowing for real-time data transfer between clients and servers. This technology is essential for many applications such as chat applications, live notifications, and any application requiring a real-time experience. In this post, we’ll explore how to implement WebSockets in a Spring Boot application.

What is WebSocket?

WebSocket is a protocol that enables interactive communication sessions between a user’s browser and a server. It allows both the client and server to send messages independently, making it suitable for applications that need real-time communication.

Setting Up WebSockets in Spring Boot

To get started with WebSockets in a Spring Boot application, you will need to add the necessary dependencies and configure your WebSocket setup.

1. Adding Dependencies

Include the following dependency in your pom.xml to enable WebSocket support in Spring Boot:

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

2. Configuring WebSocket

Create a configuration class to enable WebSocket support:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new MessageWebSocketHandler(), "/ws/messages").setAllowedOrigins("*");
    }
}

3. Creating a WebSocket Handler

You need to create a handler to manage the WebSocket messages:

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class MessageWebSocketHandler extends TextWebSocketHandler {

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // Echo back the received message (for example)
        session.sendMessage(new TextMessage("Received: " + message.getPayload()));
    }
}

Creating a Simple Web Interface

To test the WebSocket connection, create a simple HTML page with JavaScript:

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Test</title>
</head>
<body>
    <h1>WebSocket Example</h1>
    <button onclick="sendMessage()">Send Message</button>
    <script>
        const socket = new WebSocket("ws://localhost:8080/ws/messages");

        socket.onmessage = function(event) {
            console.log(event.data);
            alert(event.data);
        };

        function sendMessage() {
            socket.send("Hello from client!");
        }
    </script>
</body>
</html>

Running Your Application

Start your Spring Boot application, and open the HTML page in your browser. Click the “Send Message” button, and you should see an alert with the message received from the WebSocket server.

Conclusion

By implementing WebSockets in your Spring Boot application, you can create powerful real-time communication features that enhance the user experience. The simplicity of Spring Boot combined with WebSocket support allows developers to build dynamic applications seamlessly.

For more detailed insights on advanced usage of WebSockets and other Spring features, check out the comprehensive resources at ITER Academy, where you can further develop your Spring knowledge.

To learn more about ITER Academy, visit our website.

Scroll to Top