This website uses cookies to enhance the user experience

WebSocket and Real-time Applications

Share:

As our digital world continues to evolve, the need for creating real-time applications becomes increasingly critical. Applications in which response times require a real-time level of interaction, for instance, gaming applications, chat applications, and collaboration tools, all must maintain fast, open channels of communication. In this chapter, we will dive into how one can indulge in building real-time applications using WebSocket in Nest.js.

WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection permitting messages to be passed back and forth while keeping the connection open. In contrast to the traditional request-response model, WebSocket provides an interactive connection between the client and the server.

In the context of Nest.js, WebSocket is a part of the broader package called "@nestjs/platform-socket.io" which is built on top of Socket.IO. This socket.io provides the ability to establish a real-time, bi-directional, and event-based communication among the server and the client.

Movie Microservice and Character Notification

To demonstrate how WebSocket works in Nest.js, let's build a simple movie microservice where users are notified in real-time when a new character is added to the movie.

First, for our movie microservice, we can create our project using the Nest CLI:

$ npm i -g @nestjs/cli
$ nest new movie-microservice

We navigate into our new project and install the @nestjs/platform-socket.io and socket.io-client packages:

$ cd movie-microservice
$ npm install @nestjs/platform-socket.io socket.io-client

Next, let's create a gateway. A gateway in Nest.js context, is a class decorated with the @WebSocketGateway() decorator.

$ nest generate gateway movie

In the generated movie.gateway.ts file, we will create our first event handler to handle the "events.addCharacter":

import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';

@WebSocketGateway()
export class MovieGateway {
  @SubscribeMessage('events.addCharacter')
  handleAddCharacterEvent(client, payload): string {
    return 'Character added!';
  }
}

In the above code, we defined a handler for the 'events.addCharacter' event using the @SubscribeMessage decorator. When the event occurs, a message 'Character added!' is sent to all connected clients.

Next, we need a way to emit 'events.addCharacter' event from within our application. To achieve this, we can create a simple POST endpoint in our 'movie.controller.ts' as follows:

import { Body, Post, Req } from "@nestjs/common";
import { MessageBody } from "@nestjs/websockets";
import { MovieGateway } from "./movie.gateway";

@Controller('movies')
export class MovieController {
  constructor(private movieGateway: MovieGateway) {}

  @Post('/characters')
  addCharacter(@Req() request, @Body('characterName') characterName) {
    this.movieGateway.server.emit('events.addCharacter', characterName);
    return 'Character added successfully!';
  }
}

In the above code snippet, we inject our MovieGateway service and call the server.emit() method to transmit the 'events.addCharacter' event upon a POST request to '/movies/characters'.

Now, our movie microservice is ready and can add new characters and notify about them in real-time. The client could be another microservice or user interface that connects to this WebSocket and listens for the events it is interested in. Let's create a simple client to listen to our server events.

In your main.ts file or any other dedicated client file:

import * as io from 'socket.io-client';

const socket = io('http://localhost:3000');
socket.on('events.addCharacter', (characterName) => console.log(`New character added: ${characterName}`));

In the above code, we create a connection to the WebSocket server and tell the client what to do when it receives the 'events.addCharacter' event.

Summing up

This chapter introduced you to the world of WebSocket and real-time applications with Nest.js. You should now have a basic understanding of building real-time functionality with WebSockets into your Nest.js applications. Remember to always keep the communication channel open and interactive, this way the server can share updates with clients instantly. Under the hood, all of this happens because the WebSocket protocol realizes a full-duplex connection, allowing both server and client to send and receive data simultaneously.

Just imagine the immense possibilities you can achieve with this technology, ranging from real-time dashboards, activity streams, IoT, to interactive games, and many more. In the next chapter, we will focus on how to handle and manage errors in WebSocket connections.

0 Comment


Sign up or Log in to leave a comment


Recent job openings

India, Gurugram, HR

Remote

Full-time

Python

Python

SQL

SQL

+6

posted 5 days ago

Brazil, São Paulo, São Paulo

Remote

Full-time

Docker

Docker

posted 5 days ago

Spain, Barcelona, Catalonia

Remote

Python

Python

posted 5 days ago

Pakistan, Lahore, Punjab

Remote

Full-time

Python

Python

SQL

SQL

+5

posted 5 days ago

Pakistan, Lahore, Punjab

Remote

Full-time

JavaScript

JavaScript

HTML

HTML

+5

posted 5 days ago