NestJS hỗ trợ WebSockets qua @WebSocketGateway() decorator, tích hợp với socket.io hoặc ws. Gateway là class đặc biệt giống Controller nhưng xử lý WebSocket events.
Gateway implement 3 interfaces: OnGatewayInit (sau khi khởi tạo), OnGatewayConnection (client connect), OnGatewayDisconnect (client disconnect). @WebSocketServer() inject server instance. @SubscribeMessage('event') handle event từ client, tương tự @Get() trong controller. @MessageBody() và @ConnectedSocket() là param decorators cho WS.
Broadcast: this.server.emit() gửi cho tất cả, this.server.to(room).emit() gửi cho room, client.to(room).emit() gửi cho room trừ sender. Guards và Interceptors hoạt động với WS Gateway giống HTTP. Namespace với namespace: '/chat' trong decorator options để tách biệt connections.