Consider a NestJS WebSocket gateway that broadcasts a message to all connected clients using this.server.emit('message', data). What will the clients receive?
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets'; import { Server } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @WebSocketServer() server: Server; broadcastMessage(data: string) { this.server.emit('message', data); } }
Think about how emit works on the server instance in Socket.IO.
Using this.server.emit sends the event to all connected clients, broadcasting the message globally.
In a NestJS WebSocket gateway, after calling this.server.emit('update', payload), what happens to the list of connected clients?
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets'; import { Server } from 'socket.io'; @WebSocketGateway() export class UpdateGateway { @WebSocketServer() server: Server; sendUpdate(payload: any) { this.server.emit('update', payload); } }
Broadcasting sends messages but does not affect client connections.
Broadcasting messages does not change the connection state of clients; all remain connected unless explicitly disconnected.
Given a NestJS WebSocket gateway, which code snippet correctly broadcasts a message only to clients in the room 'chat-room'?
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets'; import { Server } from 'socket.io'; @WebSocketGateway() export class RoomGateway { @WebSocketServer() server: Server; broadcastToRoom(message: string) { // Which option is correct here? } }
Use the Socket.IO method to target a specific room.
The to method targets a room, and emit sends the event to that room's clients.
In a NestJS WebSocket gateway, a developer tries to broadcast a message using this.server.broadcast.emit('event', data) but it fails. Why?
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets'; import { Server } from 'socket.io'; @WebSocketGateway() export class DebugGateway { @WebSocketServer() server: Server; sendEvent(data: any) { this.server.broadcast.emit('event', data); } }
Consider where the 'broadcast' property is available in Socket.IO.
The broadcast property exists on socket instances to send to all except the sender. The server instance does not have 'broadcast'.
In a NestJS application running multiple instances behind a load balancer, what must be done to ensure WebSocket broadcasts reach all clients connected to any instance?
Think about how multiple server instances share state for WebSocket events.
In clustered setups, a shared adapter like Redis is required to propagate broadcast events to all instances so all clients receive messages.