In NestJS, WebSockets allow a server and client to communicate continuously. How does this connection stay open?
Think about how a phone call stays open versus sending letters back and forth.
WebSockets establish a single TCP connection that remains open, allowing instant two-way communication without repeated handshakes.
Consider a NestJS WebSocket Gateway that listens for messages. What is the typical behavior when a message arrives?
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('message') handleMessage(@MessageBody() data: string): string { return `Received: ${data}`; } }
Think about how a chat app replies instantly when you send a message.
The Gateway listens for specific events, processes incoming messages, and can send immediate responses back to the client over the open WebSocket connection.
In NestJS WebSocket Gateway, which lifecycle method is triggered when a client disconnects?
import { WebSocketGateway, OnGatewayDisconnect } from '@nestjs/websockets'; @WebSocketGateway() export class ChatGateway implements OnGatewayDisconnect { handleDisconnect(client: any) { console.log('Client disconnected'); } }
Think about the name that suggests a client leaving or disconnecting.
The handleDisconnect() method is called automatically when a client disconnects from the WebSocket Gateway.
Choose the correct way to send a message to all clients connected to a NestJS WebSocket Gateway.
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets'; import { Server } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @WebSocketServer() server: Server; broadcastMessage(message: string) { // Fill in the blank } }
Look for the method that sends an event to all clients in Socket.IO.
The emit method sends an event with data to all connected clients in Socket.IO, which NestJS uses under the hood.
Given the following code, why does the server never log incoming messages?
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('chat') handleChat(@MessageBody() data: string) { console.log('Message:', data); } }
Check if the event names between client and server match exactly.
The server listens for 'chat' events, but if the client sends 'message' events, the handler won't trigger.