1. Install Required Dependencies
Install the WebSocket package for NestJS:
npm install @nestjs/websockets @nestjs/platform-socket.io
2. Create a Gateway
Create a WebSocket gateway in your NestJS application.
import {
WebSocketGateway,
WebSocketServer,
SubscribeMessage,
MessageBody,
ConnectedSocket,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
@WebSocketGateway({ cors: true }) // Enable CORS if Angular runs on a different domain
export class NotificationsGateway {
@WebSocketServer()
server: Server;
// Handle new connections
handleConnection(client: Socket) {
console.log(`Client connected: ${client.id}`);
}
// Handle disconnections
handleDisconnect(client: Socket) {
console.log(`Client disconnected: ${client.id}`);
}
// Listen for custom events
@SubscribeMessage('sendNotification')
handleNotification(
@MessageBody() data: { message: string },
@ConnectedSocket() client: Socket,
) {
console.log(`Received message: ${data.message}`);
// Broadcast to all clients
this.server.emit('receiveNotification', data);
}
}
3. Add the Gateway to a Module
Register the gateway in a module (e.g., AppModule
).
import { Module } from '@nestjs/common';
import { NotificationsGateway } from './notifications.gateway';
@Module({
providers: [NotificationsGateway],
})
export class AppModule {}
Leave a Reply