Topic 12: – 6 steps of Spring Boot WebSocket

Play Store Application link – Spring Boot in 13 steps – App on Google Play

This guide focuses on using WebSockets in Spring Boot for real-time communication, including setting up WebSocket endpoints, creating a simple chat application, and integrating WebSockets with STOMP for message broadcasting.

Github project link – https://github.com/kuldeep101990/Spring-Boot-WebSockets


Step 1: Setting Up a Spring Boot Project

Using Spring Initializr

  1. Visit https://start.spring.io/.
  2. Configure the project:
    • Project: Maven
    • Language: Java
    • Spring Boot Version: 3.x.x
    • Dependencies: Spring Web, Spring Boot DevTools, Spring WebSocket, Spring Messaging
  3. Click Generate to download the project ZIP and extract it.

Import into IDE

  • Import the project into your favorite IDE (IntelliJ, Eclipse, etc.) as a Maven project.

Step 2: Enabling WebSocket Support

Enable WebSocket Configuration

Create a configuration class to enable WebSocket support:

package com.example.websocketdemo.config;
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 registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").withSockJS(); // WebSocket endpoint
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic"); // Enable simple broker for message broadcasting
        registry.setApplicationDestinationPrefixes("/app"); // Prefix for sending messages
    }
}


Step 3: Creating a Simple Chat Application

Chat Controller

Create a controller to handle WebSocket messages:

package com.example.websocketdemo.controller;
import com.example.websocketdemo.model.ChatMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class ChatController {
    @MessageMapping("/sendMessage")
    @SendTo("/topic/public") // Broadcast to all subscribers on "/topic/public"
    public ChatMessage sendMessage(ChatMessage message) {
        return message;
    }
}

Chat Message Model

Create a simple model to represent the chat message:

package com.example.websocketdemo.model;
public class ChatMessage {
    private String from;
    private String text;
    // Getters and Setters
    public String getFrom() {
        return from;
    }
    public void setFrom(String from) {
        this.from = from;
    }
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
}


Step 4: Frontend for WebSocket Communication

HTML and JavaScript for Chat UI

Create a simple HTML page to interact with the WebSocket:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat Application</title>
    https://cdn.jsdelivr.net/npm/@stomp/stompjs
    https://cdn.jsdelivr.net/npm/sockjs-client@1.5.1/dist/sockjs.min.js
</head>
<body>
    <h2>Spring Boot WebSocket Chat</h2>
    <div id="chat-room">
        <div id="messages"></div>
        <input type="text" id="message-input" placeholder="Enter message...">
        <button id="send-button">Send</button>
    </div>
    <script>
        var stompClient = null;
        function connect() {
            var socket = new SockJS('/chat');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/public', function(response) {
                    showMessage(JSON.parse(response.body));
                });
            });
        }
        function sendMessage() {
            var message = document.getElementById("message-input").value;
            stompClient.send("/app/sendMessage", {}, JSON.stringify({'from': 'User', 'text': message}));
            document.getElementById("message-input").value = "";
        }
        function showMessage(message) {
            var messageElement = document.createElement('div');
            messageElement.textContent = message.from + ": " + message.text;
            document.getElementById("messages").appendChild(messageElement);
        }
        document.getElementById("send-button").addEventListener("click", sendMessage);
        connect(); // Connect to WebSocket
    </script>
</body>
</html>


Step 5: Running the Application

  1. Start the Spring Boot application.
  2. Open the HTML page in a web browser (you can serve it through Spring Boot or open it directly).
  3. Type a message in the input field and click “Send.”
  4. The message will be broadcast to all connected clients in real-time.

Step 6: Integrating WebSockets with STOMP for Message Broadcasting

In the previous steps, we already integrated STOMP with WebSockets. STOMP (Streaming Text Oriented Messaging Protocol) enables message broadcasting between clients. Here’s a brief summary:

  • STOMP is used to send messages with destinations like /app/sendMessage and /topic/public.
  • @MessageMapping is used to handle incoming messages sent by the client, and @SendTo broadcasts the message to all subscribers of a particular topic.

Conclusion

In this guide, we covered:

  1. Enabling WebSocket support in Spring Boot.
  2. Creating a simple chat application using WebSockets.
  3. Integrating WebSockets with STOMP for message broadcasting.

WebSockets and STOMP provide an efficient way to implement real-time communication, and this guide shows how to quickly get started with Spring Boot.

3 comments

  1. Những chương trình khuyến mãi hấp dẫn luôn là điểm sáng của nhà cái taptap. Với ưu đãi 1.500.000 đồng khi người chơi bet88 thực hiện nạp lần đầu, cơ hội gia tăng vốn cược chưa bao giờ dễ dàng đến thế. Không chỉ vậy, các chương trình hoàn trả cược tại casino, bắn cá, hay cá cược thể thao cũng được nhà cái taptap cập nhật liên tục với tiền thưởng không giới hạn. Khi chơi tại taptap, bạn sẽ luôn cảm nhận được sự quan tâm từ hệ thống qua các ưu đãi hàng tuần, khuyến mãi sinh nhật hay sự kiện đặc biệt. Hệ thống cá cược tại taptap luôn được nâng cấp liên tục, đảm bảo trải nghiệm chơi tốt nhất cho mọi người. Với hàng loạt trò chơi, giải đấu, tỷ lệ cược hấp dẫn cùng giao dịch rút tiền về ngân hàng dễ dàng, đây chính xác là nơi bạn cần để tham gia cá cược trực tuyến. Còn chần chờ gì nữa, hãy truy cập website 188v HIPHOP ngay để đăng ký tài khoản tapbet thôi nào! TONY03-11O

  2. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

Leave a Reply

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