WebSocket Implementation Guide Part 2

March 10, 2023

WebSocket Implementation Guide Part 2

Overview

This guide outlines the steps to integrate WebSocket functionality into a Spring Boot application, allowing users to communicate in real-time through a chat application.

Steps

  1. Add WebSocket Dependency

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-websocket</artifactId>
      <version>3.2.3</version>
    </dependency>
  2. Configure WebSocket Endpoint

    Create a WebSocketConfig class to configure WebSocket endpoints:

    @Configuration
    @EnableWebSocket
    public class WebSocketConfig implements WebSocketConfigurer {
    
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(new CustomWebSocketHandler(), "/chat").setAllowedOrigins("*");
        }
    }
  3. Define Handler and Model Object

    Define a handler (CustomWebSocketHandler) to manage WebSocket sessions and handle messages. Also, define a model object (ChatPayload) to represent the message payload:

    @Data
    @NoArgsConstructor
    public class ChatPayload {
        private String chatMsg;
        private String receiverSessionID;
    }
    
    public class CustomWebSocketHandler extends TextWebSocketHandler {
        Map<String, WebSocketSession> sessionMap = new HashMap<>();
        private Gson gson = new Gson();
    
        @Override
        public void afterConnectionEstablished(WebSocketSession session) {
            sessionMap.put(session.getId(), session);
            System.out.println(Arrays.toString(sessionMap.entrySet().toArray()));
        }
    
        @Override
        public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
            ChatPayload chatPayload = gson.fromJson((String) message.getPayload(), ChatPayload.class);
            String receiverSessionId = chatPayload.getReceiverSessionID();
            WebSocketSession webSocketSession = sessionMap.get(receiverSessionId);
            webSocketSession.sendMessage(message);
        }
    
        @Override
        public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
            sessionMap.remove(session.getId());
        }
    }
  4. Frontend Implementation

    Implement a simple HTML file with JavaScript to connect to the WebSocket server and send/receive messages:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Chat Application</title>
        <style>
            #chat {
                width: 300px;
                height: 300px;
                border: 1px solid #ccc;
                overflow-y: scroll;
                padding: 10px;
            }
        </style>
    </head>
    <body>
        <button onclick="connectToWebSocket()">Connect To WebSocket</button>
        <div id="chat"></div>
        <input type="text" id="friendId" placeholder="Friend's ID">
        <input type="text" id="message" placeholder="Type your message...">
        <button onclick="sendMessage()">Send</button>
    
        <script>
            var webSocket;
    
            function connectToWebSocket() {
                webSocket = new WebSocket("ws://localhost:8080/chat");
                webSocket.onopen = function(event) {
                    console.log("WebSocket connected");
                };
                webSocket.onmessage = function(event) {
                    const message = event.data;
                    const chatWindow = document.getElementById("chat");
                    chatWindow.innerHTML += `<div>${message}</div>`;
                    chatWindow.scrollTop = chatWindow.scrollHeight;
                };
                webSocket.onerror = function(event) {
                    console.error("WebSocket error:", event);
                };
                webSocket.onclose = function(event) {
                    console.log("WebSocket closed:", event);
                };
            }
    
            function sendMessage() {
                const friendIdInput = document.getElementById("friendId");
                const messageInput = document.getElementById("message");
                const friendId = friendIdInput.value;
                const message = messageInput.value;
    
                if (friendId && message) {
                    const payload = {
                        chatMsg: message,
                        receiverSessionID: friendId
                    };
                    webSocket.send(JSON.stringify(payload));
                    messageInput.value = "";
                } else {
                    alert("Please enter both friend's Session ID and message.");
                }
            }
        </script>
    </body>
    </html>

Conclusion

Github Link for your reference : https://github.com/terror26/WebsocketSpring
By following these steps, you can integrate WebSocket functionality into your Spring Boot application, enabling real-time communication between users. This setup allows users to connect to the WebSocket server, send messages to specific recipients, and display received messages in a chat window.


Profile picture

Created and Maintained by Kanishk Verma

Works in Goldman Sachs and trying to share little knowledge I have.

@KanishkVerma97

Comments