Real-time Data with WebSockets in Spring Boot and React

Real-time Data with WebSockets in Spring Boot and React

·

3 min read

In today's fast-paced digital world, real-time data updates are essential for creating interactive and dynamic web applications. One of the most effective ways to achieve real-time communication between a client and a server is through WebSockets. This blog will guide you through building a simple real-time application using Spring Boot for the backend and React for the frontend.

What are WebSockets?

WebSockets provide a full-duplex communication channel over a single, long-lived connection between a client and a server. Unlike HTTP, which is a request-response protocol, WebSockets enable two-way communication, allowing data to be sent and received without the need for repeated HTTP requests.

Setting Up the Backend with Spring Boot

First, let's set up a Spring Boot project. We'll use Spring Initializr to generate our project with the necessary dependencies:

  1. Spring Web: To create RESTful web services.

  2. Spring WebSocket: To support WebSocket communication.

Project Structure

Here's a basic structure of our Spring Boot application:

src
└── main
    └── java
        └── com
            └── example
                └── websocket
                    ├── WebSocketConfig.java
                    └── WebSocketController.java

WebSocket Configuration

Create a WebSocketConfig class to configure WebSocket support:

package com.example.websocket;

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("*");
    }
}

WebSocket Handler

Next, create a MyWebSocketHandler class to handle WebSocket messages:

package com.example.websocket;

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();
        // Process the message and broadcast it
        session.sendMessage(new TextMessage("Hello, " + payload + "!"));
    }
}

Setting Up the Frontend with React

Now, let's create a React application to connect to our WebSocket server and display real-time data.

Project Setup

Use Create React App to set up your project:

npx create-react-app websocket-client
cd websocket-client
npm start

WebSocket Client

In your React project, create a WebSocketComponent to handle WebSocket communication:

import React, { useEffect, useState } from 'react';

const WebSocketComponent = () => {
    const [messages, setMessages] = useState([]);
    const [input, setInput] = useState('');

    useEffect(() => {
        const socket = new WebSocket('ws://localhost:8080/ws');

        socket.onmessage = (event) => {
            setMessages((prevMessages) => [...prevMessages, event.data]);
        };

        return () => socket.close();
    }, []);

    const sendMessage = () => {
        const socket = new WebSocket('ws://localhost:8080/ws');
        socket.onopen = () => socket.send(input);
    };

    return (
        <div>
            <input
                type="text"
                value={input}
                onChange={(e) => setInput(e.target.value)}
            />
            <button onClick={sendMessage}>Send</button>
            <ul>
                {messages.map((message, index) => (
                    <li key={index}>{message}</li>
                ))}
            </ul>
        </div>
    );
};

export default WebSocketComponent;

Conclusion

By following the steps outlined above, you can create a basic real-time web application using WebSockets with Spring Boot and React. This setup allows for efficient two-way communication between the server and the client, enabling real-time updates and interactions. Whether you're building a chat application, live notifications, or real-time data dashboards, WebSockets provide a robust solution for delivering real-time experiences to your users.