How to Build a Chat Application with Spring Boot and WebSocket

In this tutorial, we will learn how to build a chat application using Spring Boot and WebSocket. WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection, making it suitable for real-time applications like chat. Spring Boot, on the other hand, is a framework that simplifies the development of Java applications.

By the end of this tutorial, you will have a fully functional chat application that allows users to send and receive messages in real-time. Let’s get started!

Prerequisites

To follow along with this tutorial, you will need the following:

  • Basic knowledge of Java and Spring Boot
  • JDK 8 or later installed on your machine
  • Maven installed on your machine
  • An integrated development environment (IDE) of your choice (e.g., IntelliJ IDEA, Eclipse)

Step 1: Set Up a Spring Boot Project

To set up a Spring Boot project, follow these steps:

  1. Open your IDE and create a new Maven project.
  2. Add the following dependencies to your pom.xml file:
<dependencies>
    <!-- Spring Boot starter dependencies -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>

    <!-- Spring Boot devtools (optional) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>

    <!-- Other dependencies -->
    <!-- Add any other dependencies you may need (e.g., for database access, security, etc.) -->
</dependencies>
  1. Create a new package com.example.chatapp for your project.
  2. Create a new class ChatApplication with the following content:
package com.example.chatapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ChatApplication {

    public static void main(String[] args) {
        SpringApplication.run(ChatApplication.class, args);
    }

}

Congratulations! You have set up a basic Spring Boot project.

Step 2: Configure WebSocket Support

To configure WebSocket support in your Spring Boot application, follow these steps:

  1. Create a new package com.example.chatapp.config inside the com.example.chatapp package.
  2. Create a new class WebSocketConfig inside the com.example.chatapp.config package with the following content:
package com.example.chatapp.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 configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }

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

The WebSocketConfig class is annotated with @Configuration to enable it as a configuration class and @EnableWebSocketMessageBroker to enable WebSocket message handling.

The configureMessageBroker method configures the message broker to enable a simple message broker that will be used to send messages to clients on specific target destinations. The /topic prefix is used for destination prefixes. The setApplicationDestinationPrefixes method is used to prefix the messages that are sent to message-handling methods.

The registerStompEndpoints method registers the /chat endpoint that clients can connect to using SockJS.

  1. Add an @ComponentScan annotation to your ChatApplication class to make sure it scans the com.example.chatapp.config package:
package com.example.chatapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.example.chatapp.config")
public class ChatApplication {

    public static void main(String[] args) {
        SpringApplication.run(ChatApplication.class, args);
    }

}

You have successfully configured WebSocket support in your Spring Boot application.

Step 3: Create a Chat Controller

Next, we will create a chat controller to handle the WebSocket requests. Follow these steps:

  1. Create a new package com.example.chatapp.controller inside the com.example.chatapp package.
  2. Create a new class ChatController inside the com.example.chatapp.controller package with the following content:
package com.example.chatapp.controller;

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

@Controller
public class ChatController {

    @MessageMapping("/chat.sendMessage")
    @SendTo("/topic/public")
    public String sendMessage(String message) {
        return message;
    }

}

The ChatController class is annotated with @Controller to indicate that it is a controller class.

The sendMessage method is annotated with @MessageMapping("/chat.sendMessage") to handle messages with the destination /chat.sendMessage. The method returns the message as a string and is sent to all subscribers of the /topic/public destination.

  1. Create a new HTML file index.html inside the src/main/resources/static directory with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat Application</title>
</head>
<body>
    <div id="messages"></div>
    <form id="message-form">
        <input type="text" id="message-input">
        <button type="submit">Send</button>
    </form>

    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script>
        var socket = new SockJS('/chat');
        var stompClient = Stomp.over(socket);

        stompClient.connect({}, function (frame) {
            console.log('Connected: ' + frame);

            stompClient.subscribe('/topic/public', function (response) {
                showMessage(response.body);
            });
        });

        var messageForm = document.getElementById('message-form');
        var messageInput = document.getElementById('message-input');

        messageForm.addEventListener('submit', function (event) {
            event.preventDefault();

            stompClient.send("/app/chat.sendMessage", {}, messageInput.value);
            messageInput.value = '';
        });

        function showMessage(message) {
            var messageElement = document.createElement('div');
            messageElement.innerText = message;
            document.getElementById('messages').appendChild(messageElement);
        }
    </script>
</body>
</html>

The index.html file is a simple HTML file with a form to send messages and a <div> element to display the received messages.

The JavaScript code establishes a WebSocket connection with the server using SockJS and Stomp. It then subscribes to the /topic/public destination to receive message updates from the server. When the form is submitted, it sends the message to the server using the /app/chat.sendMessage destination.

  1. Run your Spring Boot application by executing the main method of your ChatApplication class.
  2. Open your web browser and navigate to `http://localhost:8080`. You should see the chat application.
  3. Open multiple browser windows or tabs and start chatting!

Congratulations! You have successfully built a chat application with Spring Boot and WebSocket.

Conclusion

In this tutorial, you have learned how to build a chat application using Spring Boot and WebSocket. We configured WebSocket support in our Spring Boot application, created a chat controller to handle WebSocket requests, and developed a simple front-end interface using HTML and JavaScript. With this chat application, users can send and receive messages in real-time.

Feel free to explore more advanced features of WebSocket and Spring Boot to enhance your chat application further.

Related Post