Real-time Updating Chat Room using Angular + Spring Boot + Web Sockets

Chinthaka Jayatilake
LinkIT
Published in
3 min readOct 8, 2019
Photo by Volodymyr Hryshchenko on Unsplash

What is really the specialty when it comes to web sockets? Let's find out. We know that we can simply make a chat app by using a database and a few code lines where we store and retrieve data when required. But with web sockets is how this process happens in real-time. There will be no need to refresh the page to get new messages, yet it will be automatically updated.

So let us now see how we could implement this.

Lets us first create the Angular project.

ng new project_name

Now we will create a basic HTML page to send messages and to display the received messages. So move to the app.component.html file.

<div *ngFor="let string of greetings"> <div class="container">
<p>{{string}}</p>
</div>
</div><form #loginForm=ngForm>
<div>
<br>
<textarea autocomplete="off" placeholder="Type Your Message..." name="newmessage" [(ngModel)]="newmessage" required></textarea>
<button class="btn btn-primary" (click)="sendMessage()" [disabled]="!loginForm.valid">Send</button>
</div>
</form>

Now its time to implement the web socket in the front-end. For that, we need to move to the app.component.ts file. Here we will also be implementing a method to establish the connection with the back-end, to send messages and also to receive messages.

import { Component } from '@angular/core';
import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { title = 'WebSocketChatRoom'; greetings: string[] = []; disabled = true; newmessage: string; private stompClient = null; constructor(){} ngOnInit() { this.connect(); } setConnected(connected: boolean) { this.disabled = !connected;
if (connected) {
this.greetings = [];
}
} connect() { const socket = new SockJS('http://localhost:8080/testchat');
this.stompClient = Stomp.over(socket);
const _this = this;
this.stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
_this.stompClient.subscribe('/start/initial', function(hello){
console.log(JSON.parse(hello.body));
_this.showMessage(JSON.parse(hello.body));
});
});
}
sendMessage() { this.stompClient.send(
'/current/resume',
{},
JSON.stringify(this.newmessage)
);
this.newmessage = "";
} showMessage(message) { this.greetings.push(message); }}

Do not forget to include the below command in your polyfills.ts file.

(window as any).global = window;

It is important to make sure that all the imports which are mentioned at the beginning of the component.ts files are present in the project node modules folder. If not they must be installed as below.

npm install imported_file_name

Now we need to create our Spring Boot project. The following link will help you to create and download your Spring Boot project just by few clicks.

We need to add the below dependencies to our pom.xml file to import them to our project in order to use them.

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

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

</dependencies>

Now we need to create the configurations of our web socket. For that, we will be creating a separate class for our convenience.

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 WebSocketChatConfiguration implements WebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry config{
config.enableSimpleBroker("/start");
config.setApplicationDestinationPrefixes("/current");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry
.addEndpoint("/testchat")
.setAllowedOrigins("http://localhost:4200")
.withSockJS();
}
}

As it is done now, we move on to the final section which is the controller. Here is where we get the data from the front-end and send data back to front-end with the use of the configured web socket.

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


@Controller
public class WebSocketChatController {

@MessageMapping("/resume")
@SendTo("/start/initial")
public String chat(String msg) {
System.out.println(msg);
return msg;
}
}

With that, we have come to the end of our implementation. Definitely you must be eagerly waiting now to check whether this works. So check it out now.

The project source code can be viewed and downloaded from GitHub. You can simply add it to your project whenever required.

Hope you got an idea about how to implement web sockets in your project. You can even add a database to this app to save the messages sent and to load them each time you open the message list.

Try it out. Trust me. Only a few lines more to be added…

Cheers!! Have a pleasant day!!

Visit my Official Blog Site to send in your queries directly to me and to read more articles by me…

--

--