Building a Real-Time Web Application with Websockets, Spring Boot, and Angular

Websockets are a powerful technology that allow for real-time, two-way communication between a client and a server. In this article, we will explore how to use websockets with Spring Boot and Angular to build a real-time web application.

What is Websockets?

Websockets are a protocol that allows for real-time, two-way communication between a client and a server. Unlike traditional HTTP requests which are one-way, websockets establish a persistent connection between the client and the server, enabling real-time updates to be pushed from the server to the client as soon as they become available.

Websockets are ideal for building real-time applications such as chat applications, stock tickers, and live sports scores. They are also useful for applications that require frequent updates, such as news websites and social media platforms.

What is Spring Boot?

Spring Boot is a popular framework for building web applications in Java. It provides a simplified approach to building web applications by providing pre-configured settings and dependencies, allowing developers to focus on writing business logic rather than boilerplate code.

Spring Boot is also highly customizable, making it ideal for building complex applications that require integration with third-party services and APIs.

What is Angular?

Angular is a popular front-end framework for building dynamic web applications. It provides a comprehensive set of tools and features for building complex user interfaces, including data binding, routing, and component-based architecture.

Angular is highly scalable and can be used to build applications of any size, from small single-page applications to large enterprise applications.

Building a Real-Time Web Application with Websockets, Spring Boot, and Angular

Now that we have a basic understanding of websockets, Spring Boot, and Angular, let’s explore how to build a real-time web application using these technologies.

Step 1: Setting up the Backend with Spring Boot

The first step in building a real-time web application is to set up the backend with Spring Boot. To do this, we will create a new Spring Boot project and add the necessary dependencies.

  1. Create a new Spring Boot project using your preferred IDE or the Spring Initializr.
  2. Add the following dependencies to your project’s pom.xml file:

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

This will add the Spring Boot WebSocket starter to your project, which includes all the necessary dependencies for working with websockets in Spring Boot.

Next, we need to create a WebSocket configuration class to handle incoming WebSocket connections. Create a new class called WebSocketConfig in your project’s src/main/java directory and add the following code:

package com.example.websocketdemo.config;

import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.config.annotation.EnableWebSocket;import org.springframework.web.socket.config.annotation.WebSocketConfigurer;import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer {

@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(new SocketHandler(), “/socket”).setAllowedOrigins(“*”);}}

This code sets up a WebSocketHandlerRegistry to handle incoming WebSocket connections. It registers a new SocketHandler instance to handle incoming messages on the /socket endpoint, with the setAllowedOrigins(“*”) method allowing connections from any origin.

Next, we need to create the SocketHandler class to handle incoming WebSocket messages. Create a new class called SocketHandler in your project’s src/main/java directory and add the following code:

package com.example.websocketdemo.config;

import org.springframework.stereotype.Component;import org.springframework.web.socket.TextMessage;import org.springframework.web.socket.WebSocketSession;import org.springframework.web.socket.handler.TextWebSocketHandler;

@Componentpublic class SocketHandler extends TextWebSocketHandler {

@Overridepublic void handleTextMessage(WebSocketSession session, TextMessage message) {System.out.println(“Received message: ” + message.getPayload());}}

This code creates a new TextWebSocketHandler to handle incoming text messages on the websocket connection. The handleTextMessage method is called whenever a message is received on the connection, and simply prints the message payload to the console.

With this setup, the backend is now ready to handle incoming WebSocket connections and messages.

Step 2: Setting up the Frontend with Angular

The next step in building a real-time web application is to set up the frontend with Angular. To do this, we will create a new Angular project and add the necessary dependencies.

  1. Create a new Angular project using the Angular CLI:

ng new my-app

  1. Add the following dependencies to your project’s package.json file:

“dependencies”: {
    “@angular/animations”: “^10.1.6”,
    “@angular/common”: “^10.1.6”,
    “@angular/compiler”: “^10.1.6”,
    “@angular/core”: “^10.1.6”,
    “@angular/forms”: “^10.1.6”,
    “@angular/platform-browser”: “^10.1.6”,
    “@angular/platform-browser-dynamic”: “^10.1.6”,
    “@angular/router”: “^10.1.6”,
    “rxjs”: “^6.6.3”,
    “tslib”: “^2.0.0”,
    “zone.js”: “^0.11.3”
},
“devDependencies”: {
    “@angular/cli”: “^10.1.7”,
    “@angular/compiler-cli”: “^10.1.6”,
    “@types/jasmine”: “~3.5.0”,
    “@types/node”: “^12.11.1”,
    “codelyzer”: “^6.0.0”,
    “jasmine-core”: “~3.6.0”,
    “jasmine-spec-reporter”: “~5.0.0”,
    “karma”: “~5.0.0”,
    “karma-chrome-launcher”: “~3.1.0”,
    “karma-coverage-istanbul-reporter”: “^3.0.2”,
    “karma-jasmine”: “~3.3.0”,
    “karma-jasmine-html-reporter”: “^1.5.0”,
    “protractor”: “~7.0.0”,
    “ts-node”: “~8.3.0”,
    “tslint”: “~6.1.0”,
    “typescript”: “~4.0.2”
}

This will add the necessary Angular dependencies to your project, including the Angular core modules, RxJS, and Zone.js.

Next, we need to create a new Angular component to handle the websocket connection and messages. Create a new component called SocketComponent in your project’s src/app directory using the following command:

ng generate component socket

Next, open the SocketComponent class in your project’s src/app/socket/socket.component.ts file and add the following code:

import { Component, OnInit } from ‘@angular/core’;import { Observable } from ‘rxjs’;import { WebSocketSubject } from ‘rxjs/webSocket’;

@Component({selector: ‘app-socket’,templateUrl: ‘./socket.component.html’,styleUrls: [‘./socket.component.css’]})export class SocketComponent implements OnInit {

private socket$: WebSocketSubject;

constructor() { }

ngOnInit(): void {this.socket$ = new WebSocketSubject(‘ws://localhost:8080/socket’);this.socket$.subscribe((message) => console.log(‘Received message:’, message),(error) => console.error(error),() => console.warn(‘Completed!’));}

sendMessage(message: string): void {this.socket$.next(message);}

}

This code imports the necessary Angular modules and creates a new WebSocketSubject instance to handle the websocket connection. The ngOnInit method is called when the component is initialized and creates a new WebSocketSubject instance with the URL ws://localhost:8080/socket. The subscribe method is called to listen for incoming messages on the websocket connection, and the sendMessage method is called to send messages to the server.

Finally, we need to create the SocketComponent template to display the websocket messages. Open the SocketComponent template in your project’s src/app/socket/socket.component.html file and add the following code:

<h2>Socket Component</h2>
{{socket$ | async}}

This code simply displays the incoming websocket messages using the async pipe.

Step 3: Testing the Real-Time Web Application

With the backend and frontend set up, we can now test the real-time web application. To do this, start the Spring Boot application and the Angular application in separate terminal windows using the following commands:

mvn spring-boot:runng serve

Next, open your web browser and navigate to http://localhost:4200/socket. You should see the Socket Component displayed, with incoming websocket messages being logged to the console.

To test sending messages to the server, open the browser developer tools and enter the following command in the console:

ng.getComponent(‘app-socket’).sendMessage(‘Hello, server!’)

This will send the message “Hello, server!” to the server, which should be logged in the console output of the Spring Boot application.

Congratulations, you have now built a real-time web application with websockets, Spring Boot, and Angular!

FAQ

What is the difference between HTTP and Websockets?

HTTP is a protocol for transferring data over the web, typically used for requesting and receiving web pages and other resources. Websockets, on the other hand, are a protocol for real-time, two-way communication between a client and a server. Unlike HTTP, which is one-way, websockets establish a persistent connection between the client and the server, enabling real-time updates to be pushed from the server to the client as soon as they become available.

What are some use cases for Websockets?

Websockets are ideal for building real-time applications such as chat applications, stock tickers, and live sports scores. They are also useful for applications that require frequent updates, such as news websites and social media platforms.

What is Spring Boot?

Spring Boot is a popular framework for building web applications in Java. It provides a simplified approach to building web applications by providing pre-configured settings and dependencies, allowing developers to focus on writing business logic rather than boilerplate code.

What is Angular?

Angular is a popular front-end framework for building dynamic web applications. It provides a comprehensive set of tools and features for building complex user interfaces, including data binding, routing, and component-based architecture.

How do I test my real-time web application?

To test your real-time web application, start the Spring Boot application and the Angular application in separate terminal windows using the following commands:

mvn spring-boot:runng serve

Next, open your web browser and navigate to http://localhost:4200/socket. You should see the Socket Component displayed, with incoming websocket messages being logged to the console.

To test sending messages to the server, open the browser developer tools and enter the following command in the console:

ng.getComponent(‘app-socket’).sendMessage(‘Hello, server!’)

This will send the message “Hello, server!” to the server, which should be logged in the console output of the Spring Boot application.