Broadcasting messages lets your app send information to many users at once. It helps keep everyone updated in real time.
0
0
Broadcasting messages in NestJS
Introduction
You want to send live chat messages to all users in a chat room.
You need to update multiple clients when data changes on the server.
You want to notify all connected users about a system event.
You want to send alerts or announcements to many users simultaneously.
Syntax
NestJS
this.server.emit('eventName', data);this.server is usually a WebSocket server instance injected in your gateway.
emit sends the message to all connected clients.
Examples
Sends a 'message' event with a text to all clients.
NestJS
this.server.emit('message', { text: 'Hello everyone!' });
Broadcasts an 'update' event with a number to all connected users.
NestJS
this.server.emit('update', { count: 10 });
Sample Program
This NestJS WebSocket gateway listens for 'sendMessage' events from clients. When it gets a message, it broadcasts a 'newMessage' event with the text to all connected clients.
NestJS
import { WebSocketGateway, WebSocketServer, SubscribeMessage, MessageBody } from '@nestjs/websockets'; import { Server } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @WebSocketServer() server: Server; @SubscribeMessage('sendMessage') handleMessage(@MessageBody() message: string) { // Broadcast the message to all clients this.server.emit('newMessage', { text: message }); } }
OutputSuccess
Important Notes
Broadcasting sends messages to all connected clients, not just one.
You can use namespaces or rooms to limit broadcasting to specific groups.
Make sure to handle large numbers of clients carefully to avoid performance issues.
Summary
Broadcasting sends messages to many users at once.
Use this.server.emit inside a WebSocket gateway to broadcast.
It helps keep all clients updated in real time.