Consider a NestJS WebSocket Gateway where clients can join rooms. What is the effect of calling client.join('room1') inside a message handler?
import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets'; import { Socket } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('joinRoom') handleJoinRoom(@MessageBody() room: string, @ConnectedSocket() client: Socket) { client.join(room); } }
Think about what rooms do in socket.io and how they affect message delivery.
Calling client.join('room1') adds the client to that room. This means the client will receive messages sent to that room. It does not disconnect the client or restrict sending messages.
In NestJS, how do you define a WebSocket Gateway that listens on a custom namespace /chat?
Check the official NestJS documentation for the correct option key to specify a namespace.
The namespace option is used to specify the namespace for the gateway. Using @WebSocketGateway({ namespace: '/chat' }) correctly sets the namespace.
Given this code snippet, why might clients in the room not receive the broadcasted message?
import { WebSocketGateway, SubscribeMessage, ConnectedSocket, WebSocketServer } from '@nestjs/websockets'; import { Socket, Server } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @WebSocketServer() server: Server; @SubscribeMessage('sendMessage') handleMessage(@ConnectedSocket() client: Socket, message: string) { this.server.to('room1').emit('message', message); } handleConnection(client: Socket) { client.join('room1'); } }
Check how the server property is assigned or initialized.
The server property is declared but never assigned. Without initializing it (e.g., using @WebSocketServer() decorator), this.server.to(...) is undefined, so no messages are sent.
Assuming clients join and leave rooms as shown, how many clients remain in room42?
import { WebSocketGateway, ConnectedSocket, SubscribeMessage } from '@nestjs/websockets'; import { Socket } from 'socket.io'; @WebSocketGateway() export class RoomGateway { @SubscribeMessage('join') joinRoom(@ConnectedSocket() client: Socket) { client.join('room42'); } @SubscribeMessage('leave') leaveRoom(@ConnectedSocket() client: Socket) { client.leave('room42'); } } // Scenario: // Client A joins room42 // Client B joins room42 // Client A leaves room42 // Client C joins room42
Count clients currently in the room after all join and leave actions.
Clients A and B join, then A leaves, then C joins. So clients B and C remain in room42, total 2.
Which statement best describes the difference between namespaces and rooms in NestJS WebSocket gateways?
Think about how socket.io organizes connections and message delivery.
Namespaces create separate endpoints (paths) for WebSocket connections. Rooms are subsets inside a namespace to group clients for sending messages to specific groups.