Do you want to build a web application that allows real-time communication between the client and server? If so, you’ll need to use WebSockets, a powerful protocol that enables bidirectional, full-duplex communication over a single TCP connection.
In this guide, we’ll show you how to use NestJS, a popular Node.js framework, to implement a WebSocket server and client. We’ll cover the basics of WebSockets, how NestJS makes it easy to work with them, and provide a step-by-step example of how to build a real-time chat application.
Table of Contents
- Introduction to WebSockets
- What is NestJS?
- Setting Up Your Environment
- Creating a WebSocket Server with NestJS
- Creating a WebSocket Client with NestJS
- Building a Real-Time Chat Application
- FAQ
1. Introduction to WebSockets
WebSockets are a protocol that enables real-time communication between the client and server. Unlike HTTP, which is a request-response protocol, WebSockets allow for bidirectional, full-duplex communication over a single TCP connection. This means that both the client and server can send data to each other at any time, without having to wait for a request.
WebSockets were first introduced in 2011 and have since become a popular choice for building real-time web applications such as chat applications, online gaming, and stock trading platforms.
2. What is NestJS?
NestJS is a popular Node.js framework that provides a robust set of features for building scalable and maintainable web applications. It is built on top of Express.js and provides an opinionated architecture that promotes separation of concerns, modularization, and dependency injection.
NestJS also provides built-in support for WebSockets, making it easy to implement real-time communication in your web applications.
3. Setting Up Your Environment
Before we start building our WebSocket server and client with NestJS, we need to set up our environment. Here are the steps:
- Install Node.js and npm
- Create a new directory for your project
- Initialize your project with npm by running the command
npm init - Install NestJS by running the command
npm install -g @nestjs/cli
With these steps completed, you’re ready to start building your WebSocket server and client with NestJS.
4. Creating a WebSocket Server with NestJS
Now that we have our environment set up, let’s create our WebSocket server with NestJS. Here are the steps:
- Create a new NestJS application by running the command
nest new my-app - Change into the newly created directory by running the command
cd my-app - Generate a new controller by running the command
nest generate controller chat - Open the
chat.controller.tsfile and add the following code:
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets';import { Server } from 'socket.io';@WebSocketGateway()export class ChatGateway {@WebSocketServer() server: Server;}
This code defines a new WebSocket gateway using the @WebSocketGateway decorator provided by NestJS. We also define a server property using the @WebSocketServer decorator, which will hold a reference to the WebSocket server instance.
Next, let’s add a method to our controller that will handle incoming WebSocket connections. Add the following code to the chat.controller.ts file:
import { WebSocketGateway, WebSocketServer, OnGatewayConnection } from '@nestjs/websockets';import { Server, Socket } from 'socket.io';@WebSocketGateway()export class ChatGateway implements OnGatewayConnection {@WebSocketServer() server: Server;
handleConnection(client: Socket, ...args: any[]) {console.log('Client connected.');}}
This code adds an OnGatewayConnection interface to our controller, which provides a method called handleConnection. This method will be called whenever a new WebSocket connection is established.
For now, we’re just logging a message to the console when a new client connects. We’ll add more functionality later.
Finally, we need to modify our main.ts file to use our new ChatGateway. Open the main.ts file and modify it as follows:
import { NestFactory } from '@nestjs/core';import { AppModule } from './app.module';import { ChatGateway } from './chat.controller';async function bootstrap() {const app = await NestFactory.create(AppModule);app.enableCors();await app.listen(3000);}
bootstrap().then(() => {const chatGateway = app.get(ChatGateway);chatGateway.server.on('connection', (socket) => {console.log('Client connected.');});});
In this code, we’re creating a new instance of our ChatGateway and getting a reference to the WebSocket server instance using the server property. We’re then logging a message to the console when a new client connects.
That’s it! We’ve now created a WebSocket server with NestJS.
5. Creating a WebSocket Client with NestJS
Now that we have our WebSocket server set up, let’s create a WebSocket client with NestJS. Here are the steps:
- Create a new NestJS application by running the command
nest new my-app - Change into the newly created directory by running the command
cd my-app - Generate a new service by running the command
nest generate service chat - Open the
chat.service.tsfile and add the following code:
import { Injectable } from '@nestjs/common';import { io, Socket } from 'socket.io-client';import { Observable } from 'rxjs';@Injectable()export class ChatService {private socket: Socket;
public initSocket(): void {this.socket = io('http://localhost:3000');}
public sendMessage(message: string): void {this.socket.emit('message', message);}
public onMessage(): Observable<string> {return new Observable((observer) => {this.socket.on('message', (data: string) => observer.next(data));});}}
This code defines a new service called ChatService that uses the socket.io-client library to create a WebSocket connection to our server. We have three methods:
initSocket: initializes the WebSocket connectionsendMessage: sends a message to the serveronMessage: listens for incoming messages from the server
Now that we have our client service set up, let’s modify our app.module.ts file to use it. Open the app.module.ts file and modify it as follows:
import { Module } from '@nestjs/common';import { ChatService } from './chat.service';@Module({providers: [ChatService],})export class AppModule {}
That’s it! We’ve now created a WebSocket client with NestJS.
6. Building a Real-Time Chat Application
Now that we have our WebSocket server and client set up, let’s build a real-time chat application. Here are the steps:
- Create a new NestJS application by running the command
nest new my-app - Change into the newly created directory by running the command
cd my-app - Generate a new module by running the command
nest generate module chat - Generate a new controller by running the command
nest generate controller chat - Generate a new service by running the command
nest generate service chat - Modify the
chat.controller.tsfile to look like this:
import { Controller, Get, Render } from '@nestjs/common';import { ChatService } from './chat.service';@Controller('chat')export class ChatController {constructor(private readonly chatService: ChatService) {}
@Get()@Render('index')root() {}
@Get('messages')getMessages() {return this.chatService.getMessages();}}
This code creates a new controller that has two methods:
root: returns the HTML template for our chat applicationgetMessages: returns the list of messages stored in our service
Next, let’s create our HTML template. Create a new file called index.hbs in the views directory and add the following code:
<!DOCTYPE html><html><head><title>Real-Time Chat</title></head><body><ul id="messages"></ul><form id="chat-form"><input id="message-input" type="text" autocomplete="off" /><button type="submit">Send</button></form></body><script src="/socket.io/socket.io.js"></script><script src="/main.js"></script></html>This code creates a simple HTML template that has a form for sending messages and a list for displaying them.
Next, let’s create our client-side JavaScript code. Create a new file called main.js in the public directory and add the following code:
import { ChatService } from './chat.service';const chatService = new ChatService();const messageList = document.getElementById('messages');const chatForm = document.getElementById('chat-form');const messageInput = document.getElementById('message-input');
chatService.initSocket();
chatForm.addEventListener('submit', (e) => {e.preventDefault();chatService.sendMessage(messageInput.value);messageInput.value = '';});
chatService.onMessage().subscribe((message) => {const li = document.createElement('li');li.innerText = message;messageList.appendChild(li);});
This code creates a new instance of our ChatService and sets up event listeners for our form and WebSocket connection. When the user submits the form, we send the message to the server using our service’s sendMessage method. When we receive a message from the server, we add it to our list using the onMessage method.
Finally, we need to modify our chat.service.ts file to store and retrieve messages. Replace the contents of this file with the following code:
import { Injectable } from '@nestjs/common';import { io, Socket } from 'socket.io-client';import { Observable } from 'rxjs';@Injectable()export class ChatService {private socket: Socket;private messages: string[] = [];
public initSocket(): void {this.socket = io('http://localhost:3000');this.socket.on('message', (message: string) => {this.messages.push(message);});}
public sendMessage(message: string): void {this.socket.emit('message', message);}
public getMessages(): string[] {return this.messages;}
public onMessage(): Observable<string> {return new Observable((observer) => {this.socket.on('message', (data: string) => observer.next(data));});}}
This code adds a new messages property to our service that stores the messages sent by clients. We also modify our initSocket method to listen for incoming messages and add them to our messages array.
That’s it! We’ve now built a real-time chat application with NestJS and WebSockets.
7. FAQ
What are WebSockets?
WebSockets are a protocol that enables real-time communication between the client and server. Unlike HTTP, which is a request-response protocol, WebSockets allow for bidirectional, full-duplex communication over a single TCP connection.
What is NestJS?
NestJS is a popular Node.js framework that provides a robust set of features for building scalable and maintainable web applications. It is built on top of Express.js and provides an opinionated architecture that promotes separation of concerns, modularization, and dependency injection.
How do I set up my environment for NestJS?
To set up your environment for NestJS, you’ll need to install Node.js and npm, create a new directory for your project, initialize your project with npm by running the command npm init, and install NestJS by running the command npm install -g @nestjs/cli.
How do I create a WebSocket server with NestJS?
To create a WebSocket server with NestJS, you’ll need to create a new NestJS application, generate a new controller using the nest generate controller command, define a new WebSocket gateway using the @WebSocketGateway decorator, add a server property using the @WebSocketServer decorator, and define a handleConnection method to handle incoming WebSocket connections.
How do I create a WebSocket client with NestJS?
To create a WebSocket client with NestJS, you’ll need to create a new NestJS application, generate a new service using the nest generate service command, use the socket.io-client library to create a WebSocket connection to the server, and define methods for initializing the WebSocket connection, sending messages to the server, and listening for incoming messages.
How do I build a real-time chat application with NestJS?
To build a real-time chat application with NestJS, you’ll need to create a new NestJS application, generate a new module, controller, and service, modify the controller to return an HTML template for the chat application, add client-side JavaScript code to handle form submissions and display incoming messages, and modify the service to store and retrieve messages sent by clients.
SocketZone.com Internet Socket | Websocket Information Blog