Exploring the spring-boot-starter-websocket in Spring Boot

WebSockets provide a full-duplex communication channel over a single, long-lived connection, making them ideal for applications that require real-time updates, such as chat applications, live notifications, and collaborative tools. In this blog post, we’ll dive into the spring-boot-starter-websocket starter in Spring Boot and walk through a simple example to demonstrate its capabilities.

Step 1: Setting Up the Project

First, create a new Spring Boot project using Spring Initializr. Select Maven Project, Java, and Spring Boot 3.0.0 or later. Add the following dependencies:

  • Spring Web
  • Spring WebSocket

Alternatively, you can add the dependencies directly to your pom.xml:

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

Step 2: Configuring WebSocket

Create a configuration class to enable WebSocket support and configure the message broker.

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: Creating a Message Model

Define a simple message model that will be used to send and receive messages.

public class ChatMessage {
    private String content;
    private String sender;

    // Getters and setters
}

Step 4: Creating a Controller

Create a controller to handle incoming WebSocket messages and broadcast them to subscribed clients.

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class ChatController {

    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public ChatMessage send(ChatMessage message) {
        return message;
    }
}

Step 5: Creating the Frontend

Create an HTML file to interact with the WebSocket server. This example uses plain JavaScript to establish a WebSocket connection and send/receive messages.

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Chat</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.1/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script>
        var stompClient = null;

        function connect() {
            var socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/messages', function (message) {
                    showMessage(JSON.parse(message.body));
                });
            });
        }

        function sendMessage() {
            var messageContent = document.getElementById('message').value;
            var sender = document.getElementById('sender').value;
            stompClient.send("/app/chat", {}, JSON.stringify({'content': messageContent, 'sender': sender}));
        }

        function showMessage(message) {
            var response = document.getElementById('response');
            var p = document.createElement('p');
            p.appendChild(document.createTextNode(message.sender + ": " + message.content));
            response.appendChild(p);
        }
    </script>
</head>
<body onload="connect()">
    <div>
        <input type="text" id="sender" placeholder="Your name"/>
        <input type="text" id="message" placeholder="Your message"/>
        <button onclick="sendMessage()">Send</button>
    </div>
    <div id="response"></div>
</body>
</html>

Conclusion

The spring-boot-starter-websocket starter simplifies the process of setting up WebSocket communication in a Spring Boot application. By following the steps outlined in this blog post, you can create a basic chat application that demonstrates the power and flexibility of WebSockets. This setup can be extended to build more complex real-time applications, such as live notifications, collaborative tools, and more.

Happy coding! 🚀


Feel free to reach out if you have any questions or need further assistance with Spring Boot and WebSockets!

Post a Comment

Previous Post Next Post