Chat Room Project using Spring Boot Web Socket step by step
Chat Room Project using Spring Boot Web Socket step by step

In this video, we are going to learn how to create a real-time chat room application using spring boot web socket step by step. In this video, we are going to use spring boot as a backend and javascript as a frontend for creating a simple project.

 

Source Code:

 

application.properties

server.port=9090

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.chat.app</groupId>
	<artifactId>chatroomapp</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>chatroomapp</name>
	<description>This is chat room create by Me</description>
	<properties>
		<java.version>16</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-websocket</artifactId>
		</dependency>

		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>webjars-locator-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>sockjs-client</artifactId>
			<version>1.0.2</version>
		</dependency>
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>stomp-websocket</artifactId>
			<version>2.3.3</version>
		</dependency>
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>bootstrap</artifactId>
			<version>5.0.2</version>
		</dependency>
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>3.1.1-1</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

 

ChatroomappApplication.java

package com.chat.app;

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

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

}

Config.java

package com.chat.app.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 Config implements WebSocketMessageBrokerConfigurer {

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

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
}

 

Message.java

package com.chat.app.models;

public class Message {

    private String name;
    private String content;

    public Message(String name, String content) {
        this.name = name;
        this.content = content;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

 

MessageController.java

package com.chat.app.controllers;

import com.chat.app.models.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MessageController {


    @MessageMapping("/message")
    @SendTo("/topic/return-to")
    public Message getContent(@RequestBody Message message) {

//        try {
//            //processing
////            Thread.sleep(2000);
//
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return message;
    }

}

 

index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Chat Room </title>

    <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="/style.css">

    <script src="/webjars/jquery/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script src="/script.js"></script>

</head>
<body class="bg-dark " >

<div id="name-from" class="bg-primary d-flex align-items-center">

    <div class="container-fluid">

        <div class="row">

            <div class="col-md-4 offset-md-4">


                <div class="input-group">

                    <input type="text"
                           placeholder="Enter your name"
                           id="name-value"
                           autofocus
                           class="form-control"
                        >

                    <div class="input-group-append">

                        <button class="btn btn-dark" id="login">Enter</button>

                    </div>



                    </div>



                </div>

            </div>

        </div>

    </div>

<div id="chat-room" class="d-none">


    <div class="container-fluid">

        <div class="row">


            <div class="col-md-6 offset-md-3">


                <div class="card mt-3">
                    <div class="card-header">

                        <h3 id="name-title"></h3>

                    </div>
                    <div class="card-body">

                        <div class="input-group">

                            <input type="text"
                                   placeholder="Enter your message "
                                   id="message-value"
                                   autofocus
                                   class="form-control"
                            >

                            <div class="input-group-append">

                                <button class="btn btn-dark" id="send-btn">Send</button>
                                <button class="btn btn-dark" id="logout">Logout</button>

                            </div>



                        </div>


                        <div class="table-responsive mt-3">

                            <table id="message-container-table">



                            </table>

                        </div>


                    </div>
                </div>

            </div>
        </div>

    </div>


</div>


</body>
</html>

 

style.css

#name-from{
height: 100vh;
}

 

script.js

var stompClient=null



   function sendMessage(){


    let jsonOb={
        name:localStorage.getItem("name"),
        content:$("#message-value").val()
    }

    stompClient.send("/app/message",{},JSON.stringify(jsonOb));



   }



function connect()
{

        let socket=new SockJS("/server1")

        stompClient=Stomp.over(socket)

        stompClient.connect({},function(frame){

            console.log("Connected : "+frame)

            $("#name-from").addClass('d-none')
              $("#chat-room").removeClass('d-none')


                //subscribe
                stompClient.subscribe("/topic/return-to",function(response){

                        showMessage(JSON.parse(response.body))

                })



        })

}


 function showMessage(message)
 {

    $("#message-container-table").prepend(`<tr><td><b>${message.name} :</b> ${message.content}</td></tr>`)

 }





$(document).ready((e)=>{


   $("#login").click(()=>{


       let name=$("#name-value").val()
       localStorage.setItem("name",name)
       $("#name-title").html(`Welcome , <b>${name} </b>`)
       connect();


   })

   $("#send-btn").click(()=>{
    sendMessage()
   })

$("#logout").click(()=>{

    localStorage.removeItem("name")
    if(stompClient!==null)
    {
        stompClient.disconnect()

         $("#name-from").removeClass('d-none')
         $("#chat-room").addClass('d-none')
         console.log(stompClient)
    }

})

})