Skip to content
GitHub Twitter

Springing into Real-Time: Leveraging WebSockets in Spring Boot Applications

img.png

Introduction

In the dynamic realm of Spring Boot development, the need for real-time communication between clients and servers has become increasingly prevalent. Thankfully, Spring Boot provides seamless integration with WebSockets, empowering developers to unlock the power of real-time interactions in their applications. By combining the robustness of Spring Boot with the bidirectional capabilities of WebSockets, a new world of real-time possibilities emerges, enabling developers to craft highly interactive and responsive web experiences.

Project Setup

Select the required libraries needed for websocket support (similar as the screenshot below)

img.png

Configuration

Similar to other configuration patterns, using the WebSocketConfigurer you can set the base path of the websocket endpoint and also register a custom message handler for the messages we will receive.

If let's say you want a game application, you can set the base path to /game.

@EnableWebSocket
@Configuration
public class DefaultWebsocketConfigurer implements WebSocketConfigurer {

    private final SocketTextHandler socketTextHandler;

    public DefaultWebsocketConfigurer(SocketTextHandler socketTextHandler) {
        this.socketTextHandler = socketTextHandler;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(socketTextHandler, "/game");
    }
}

Handle messages

With our custom text handler extending the TextWebSocketHandler, we have the ability to override default behaviors and implement a personalized format for messages. This format acts as a contract, establishing the communication protocol between the client and the server. By customizing the message format, we can define specific data structures, encoding schemes, or any other requirements that align with our application's needs. This flexibility allows us to tailor the message handling process to suit the unique requirements of our client-server interaction.

@Component
public class SocketTextHandler extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        session.sendMessage(new TextMessage("Ok I took the message thanks"));
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("Connected, creating a user state");
        super.afterConnectionEstablished(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("Connection closed, do something now");
        super.afterConnectionClosed(session, status);
    }
}

Test & Verify

Insomnia Rest Client has built in support for websockets so calling the /game route looks like this

img.png