Step-by-Step Guide to Implementing WebSockets in Spring Boot

WebSockets enable full-duplex communication between a client and a server, making them ideal for real-time applications like chat systems, notifications, and live updates. This guide walks through implementing WebSockets in a Spring Boot application.

1. Add Dependencies

To enable WebSockets, include the following dependency in your pom.xml:

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

2. Configure WebSockets in Spring Boot

Create a WebSocket 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 MyWebSocketHandler(), "/ws").setAllowedOrigins("*");
    }
}

3. Implement a WebSocket Handler

Create a handler to manage WebSocket messages:

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

public class MyWebSocketHandler extends TextWebSocketHandler {
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("Received message: " + payload);
        session.sendMessage(new TextMessage("Echo: " + payload));
    }
}

4. Testing WebSocket Connection

Use WebSocket testing tools like wscat or a browser console to connect and send messages:

wscat -c ws://localhost:8080/ws

5. Using STOMP for Advanced WebSockets

If you need more advanced WebSocket features, use Spring’s STOMP (Simple Text Oriented Messaging Protocol) support:

5.1 Add STOMP Dependency

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

5.2 Configure STOMP WebSocket

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 StompWebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/stomp").setAllowedOrigins("*").withSockJS();
    }
}

5.3 Create a Controller for Messaging

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

@Controller
public class WebSocketController {
    @MessageMapping("/message")
    @SendTo("/topic/messages")
    public String processMessage(String message) {
        return "Received: " + message;
    }
}

5.4 Test STOMP WebSockets

Connect using a WebSocket client like SockJS or StompJS in JavaScript:

const socket = new SockJS('http://localhost:8080/stomp');
const stompClient = Stomp.over(socket);
stompClient.connect({}, function () {
    stompClient.subscribe('/topic/messages', function (response) {
        console.log('Received:', response.body);
    });
    stompClient.send("/app/message", {}, "Hello WebSocket");
});

Conclusion

WebSockets in Spring Boot allow real-time, bidirectional communication. Depending on your needs, you can use a basic WebSocket handler or leverage STOMP for advanced messaging. Implementing WebSockets correctly enhances performance and user experience in applications requiring real-time updates.

Related post

Leave a Reply

Your email address will not be published. Required fields are marked *