In NestJS, using WebSocket typically involves working with libraries such as Socket.IO or ws alongside NestJS's abstraction layer for easy integration and maintenance. NestJS provides a module named @nestjs/websockets that includes decorators and classes required for interacting with WebSocket.
1. Install necessary packages
First, ensure that you have installed the @nestjs/websockets module and the socket.io library (if you choose to use Socket.IO):
bashnpm install @nestjs/websockets @nestjs/platform-socket.io socket.io
2. Create Gateway
In NestJS, you can create a Gateway, which is a class decorated with @WebSocketGateway(), handling WebSocket connections. For example:
typescriptimport { WebSocketGateway, WebSocketServer, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway({ cors: true }) export class EventsGateway { @WebSocketServer() server: Server; @SubscribeMessage('message') handleMessage(@MessageBody() data: string, @ConnectedSocket() client: Socket): void { client.emit('message', data); // Echo the message back to the client } }
In this example, the EventsGateway class uses the @WebSocketGateway decorator to create a WebSocket server. We listen for the message event and define a handler function handleMessage to process received messages.
3. Register Gateway in Module
Next, you need to register this Gateway in a NestJS module:
typescriptimport { Module } from '@nestjs/common'; import { EventsGateway } from './events.gateway'; @Module({ providers: [EventsGateway], }) export class AppModule {}
This way, the EventsGateway will be recognized by the NestJS framework and automatically start the WebSocket server upon application startup.
4. Connect WebSocket Client
Clients can use the socket.io-client library or other WebSocket client libraries to connect to the server:
javascript// Using socket.io-client in the client-side code const socket = io('http://localhost:3000'); socket.on('message', function(data) { console.log('Received message:', data); }); socket.emit('message', 'Hello, server!'); // Send a message to the server
The above client-side code example demonstrates using socket.io-client to connect to the NestJS service and listen for the message event. The client also sends a message event to the server using emit.
5. Using Advanced Features
The NestJS WebSocket module also supports advanced features such as namespaces/rooms, exception filters, pipes, interceptors, and guards, enabling developers to build WebSocket applications with complex logic and security.
For example, if you want to send messages only to clients in a specific room, you can do the following:
typescript@SubscribeMessage('joinRoom') async handleJoinRoom(@MessageBody() room: string, @ConnectedSocket() client: Socket) { client.join(room); // Join the specified room } @SubscribeMessage('leaveRoom') async handleLeaveRoom(@MessageBody() room: string, @ConnectedSocket() client: Socket) { client.leave(room); // Leave the specified room } async sendMessageToRoom(room: string, message: string) { this.server.to(room).emit('message', message); // Emit a message to all clients in the specified room }
In this example, we create event handlers for joining and leaving rooms, as well as a function to send messages to all clients in a specified room.
By following these steps, you can set up and use WebSocket communication in NestJS. Of course, adjustments and optimizations may be needed based on the specific application context.