How to Implement WebSockets With Java Spring Boot

How to Implement WebSockets With Java Spring Boot

WebSockets provide a full-duplex communication channel over a single TCP connection, making them ideal for scenarios where real-time data exchange is essential. Implementing WebSockets with Java Spring Boot can enhance your web applications by allowing server-side and client-side communication to occur seamlessly. Here’s a detailed guide on how to implement WebSockets in your Spring Boot application.

Step 1: Set Up Your Spring Boot Project

To start implementing WebSockets, you first need a Spring Boot project. You can create a new project through Spring Initializr or your favorite IDE. Ensure you include the following dependencies:

  • Spring Web
  • Spring WebSocket

Once you’ve set up your project, your pom.xml file might look something like this:


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

Step 2: Create WebSocket Configuration

Next, you need to create a configuration class to register the WebSocket handler. This class will extend AbstractWebSocketMessageBrokerConfigurer and override the registerStompEndpoints method.


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

Step 3: Create a Message Controller

Now, create a message controller to handle incoming WebSocket messages. This controller will map messages sent from the client to specific methods using STOMP protocols.


import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class MessageController {
@MessageMapping("/send")
    @SendTo("/topic/messages")
    public String sendMessage(String message) {
        return message;
    }
}

Step 4: Create HTML and JavaScript Client

To test your WebSocket setup, create a simple HTML file that will act as the client. You’ll utilize the SockJS library and STOMP.js for connecting to the WebSocket server.


<!DOCTYPE html>
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.0.3/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.0/stomp.min.js"></script>
</head>
<body>
    <div id="messages"></div>
    <input type="text" id="message">
    <button onclick="sendMessage()">Send</button>
<script>
        var socket = new SockJS('/ws');
        var stompClient = Stomp.over(socket);
        
        stompClient.connect({}, function (frame) {
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/messages', function (message) {
                document.getElementById('messages').innerHTML += '<p>' + message.body + '</p>';
            });
        });
function sendMessage() {
            var message = document.getElementById('message').value;
            stompClient.send("/app/send", {}, message);
        }
    </script>
</body>
</html>