NestJS Enterprise Backend APIs · บทเรียน

เกตเวย์ WebSocket ด้วยอะแดปเตอร์ Socket.IO

นำตัวจัดการ @WebSocketGateway ห้อง และฮุกวงจรชีวิตไปใช้งานสำหรับการสื่อสารแบบสด

บทเรียน 1 จาก 413 ขั้นตอน

เกตเวย์ WebSocket ด้วยอะแดปเตอร์ Socket.IO เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Gateways Exist

REST handles request/response, but real-time features (chat, presence, live dashboards) need a persistent, bidirectional channel. NestJS wraps this with a WebSocket Gateway.

  • A gateway is a provider decorated with @WebSocketGateway().
  • By default Nest uses the Socket.IO platform adapter (@nestjs/platform-socket.io).
  • Gateways are normal Nest classes: they support dependency injection, guards, pipes, and interceptors just like controllers.

Install the deps with npm i @nestjs/websockets @nestjs/platform-socket.io socket.io.

Declaring a Gateway

Decorate a class with @WebSocketGateway() and register it as a provider in a module. You can pass a port and options such as namespace and CORS config.

  • @SubscribeMessage('event') binds a handler to an inbound Socket.IO event.
  • The return value (or a WsResponse) is emitted back to the calling client.

Below, clients sending ping receive a pong reply.

import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets';

@WebSocketGateway({ namespace: '/chat', cors: { origin: '*' } })
export class ChatGateway {
  @SubscribeMessage('ping')
  handlePing(@MessageBody() data: string): { event: string; data: string } {
    return { event: 'pong', data: `received: ${data}` };
  }
}

Accessing the Server Instance

To broadcast to many clients you need the underlying Socket.IO Server. Inject it with the @WebSocketServer() property decorator.

  • server.emit('event', payload) sends to every connected client in the namespace.
  • This is the foundation for fan-out features like global announcements.
import { WebSocketGateway, WebSocketServer, SubscribeMessage, MessageBody } from '@nestjs/websockets';
import { Server } from 'socket.io';

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway {
  @WebSocketServer()
  server: Server;

  @SubscribeMessage('broadcast')
  handleBroadcast(@MessageBody() message: string): void {
    this.server.emit('announcement', message);
  }
}

The Connected Socket

Each client has its own Socket. Inject it per-handler with @ConnectedSocket() to read auth data, the socket id, or to reply only to that client.

  • client.emit(...) targets just the sender.
  • client.id uniquely identifies the connection.
  • client.handshake exposes headers, query, and auth handed in at connect time.
import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets';
import { Socket } from 'socket.io';

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway {
  @SubscribeMessage('whoami')
  whoAmI(@ConnectedSocket() client: Socket, @MessageBody() _: unknown): void {
    client.emit('identity', { id: client.id, token: client.handshake.auth?.token });
  }
}

Lifecycle Hooks

Gateways can implement lifecycle interfaces to react to connection events:

  • OnGatewayInit → afterInit(server) runs once the server is ready.
  • OnGatewayConnection → handleConnection(client) fires per new client.
  • OnGatewayDisconnect → handleDisconnect(client) fires when a client leaves.

Use these for presence tracking, auth on connect, and cleanup.

import { WebSocketGateway, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { Logger } from '@nestjs/common';

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  private readonly logger = new Logger(ChatGateway.name);

  afterInit(server: Server): void {
    this.logger.log('Gateway initialized');
  }

  handleConnection(client: Socket): void {
    this.logger.log(`Client connected: ${client.id}`);
  }

  handleDisconnect(client: Socket): void {
    this.logger.log(`Client disconnected: ${client.id}`);
  }
}

Rooms: Grouping Sockets

A room is a server-side label you attach to sockets so you can broadcast to a subset. A socket can belong to many rooms.

  • client.join('room') adds the socket to a room.
  • client.leave('room') removes it.
  • Socket.IO automatically puts each socket in a room named after its own client.id.

Rooms are how you build per-channel chat, per-tenant dashboards, or per-document collaboration.

import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets';
import { Socket } from 'socket.io';

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway {
  @SubscribeMessage('joinRoom')
  joinRoom(@ConnectedSocket() client: Socket, @MessageBody() room: string): void {
    client.join(room);
    client.emit('joined', room);
  }
}

Broadcasting to a Room

Target a room with server.to('room').emit(...). To exclude the sender, emit from the client socket: client.to('room').emit(...) sends to everyone in the room except that client.

  • server.to(room).emit(...) → everyone in the room.
  • client.to(room).emit(...) → everyone in the room but the sender.
import { WebSocketGateway, WebSocketServer, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('sendToRoom')
  sendToRoom(
    @ConnectedSocket() client: Socket,
    @MessageBody() body: { room: string; text: string },
  ): void {
    client.to(body.room).emit('message', { from: client.id, text: body.text });
  }
}

Acknowledgements with WsResponse

Socket.IO supports request/response style acknowledgements. In Nest you can return a value, a WsResponse<T> object, or even an Observable that streams multiple emissions back.

  • Return { event, data } to emit a named event back to the caller.
  • Returning an Observable emits one message per value, useful for progress updates.
import { WebSocketGateway, SubscribeMessage, MessageBody, WsResponse } from '@nestjs/websockets';
import { from, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@WebSocketGateway({ namespace: '/jobs' })
export class JobsGateway {
  @SubscribeMessage('countdown')
  countdown(@MessageBody() n: number): Observable<WsResponse<number>> {
    const ticks = Array.from({ length: n }, (_, i) => n - i);
    return from(ticks).pipe(map((value) => ({ event: 'tick', data: value })));
  }
}

Validation with Pipes

Gateways reuse Nest's ValidationPipe, but errors are thrown as WsException rather than HTTP exceptions. Apply the pipe at the handler or gateway level and validate a DTO via @MessageBody().

  • Set transform: true so plain payloads become class instances.
  • A WsException is serialized to an exception event on the client.
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets';
import { UsePipes, ValidationPipe } from '@nestjs/common';
import { IsString, MinLength } from 'class-validator';

class SendMessageDto {
  @IsString() @MinLength(1)
  text: string;
}

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway {
  @UsePipes(new ValidationPipe({ transform: true }))
  @SubscribeMessage('send')
  send(@MessageBody() dto: SendMessageDto): { event: string; data: string } {
    return { event: 'sent', data: dto.text };
  }
}

Authenticating on Connect

Authenticate clients during handleConnection by reading the token from the handshake and disconnecting unauthorized sockets early. Storing the user on client.data makes it available to every later handler.

  • Token usually arrives via handshake.auth.token or an Authorization header.
  • Call client.disconnect() to reject bad clients before they join rooms.
import { WebSocketGateway, OnGatewayConnection } from '@nestjs/websockets';
import { Socket } from 'socket.io';
import { JwtService } from '@nestjs/jwt';

@WebSocketGateway({ namespace: '/chat' })
export class ChatGateway implements OnGatewayConnection {
  constructor(private readonly jwt: JwtService) {}

  async handleConnection(client: Socket): Promise<void> {
    try {
      const token = client.handshake.auth?.token as string;
      client.data.user = await this.jwt.verifyAsync(token);
    } catch {
      client.emit('error', 'Unauthorized');
      client.disconnect();
    }
  }
}

Swapping the Adapter for Scale

Out of the box, Socket.IO state lives in a single process. To run multiple Nest instances behind a load balancer you must share room/emit state. Use a custom adapter with the Redis adapter so broadcasts reach clients on other nodes.

  • Subclass IoAdapter and attach @socket.io/redis-adapter in createIOServer.
  • Register it via app.useWebSocketAdapter(new RedisIoAdapter(app)) in main.ts.
import { IoAdapter } from '@nestjs/platform-socket.io';
import { ServerOptions } from 'socket.io';
import { createAdapter } from '@socket.io/redis-adapter';
import { createClient } from 'redis';

export class RedisIoAdapter extends IoAdapter {
  private adapterConstructor: ReturnType<typeof createAdapter>;

  async connectToRedis(): Promise<void> {
    const pub = createClient({ url: 'redis://localhost:6379' });
    const sub = pub.duplicate();
    await Promise.all([pub.connect(), sub.connect()]);
    this.adapterConstructor = createAdapter(pub, sub);
  }

  createIOServer(port: number, options?: ServerOptions): any {
    const server = super.createIOServer(port, options);
    server.adapter(this.adapterConstructor);
    return server;
  }
}

Quick Check

Test your understanding of room broadcasting semantics.

Recap

You built a real-time layer with NestJS WebSocket gateways on the Socket.IO adapter:

  • Gateway basics: @WebSocketGateway() providers with @SubscribeMessage handlers; inject the server via @WebSocketServer() and the per-client socket via @ConnectedSocket().
  • Lifecycle hooks: afterInit, handleConnection, and handleDisconnect for init, presence, and cleanup.
  • Rooms: client.join/leave, then server.to(room) for everyone or client.to(room) to exclude the sender.
  • Robustness: validate payloads with ValidationPipe (errors become WsException), authenticate in handleConnection, and use acknowledgements/Observables for replies.
  • Scale: swap in a Redis-backed IoAdapter so broadcasts work across multiple instances.
เริ่มต้นได้ฟรี

เรียนรู้ TypeScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
20
บทเรียน
76

คำถามที่พบบ่อย

บทเรียน “เกตเวย์ WebSocket ด้วยอะแดปเตอร์ Socket.IO” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “เกตเวย์ WebSocket ด้วยอะแดปเตอร์ Socket.IO” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “เกตเวย์ WebSocket ด้วยอะแดปเตอร์ Socket.IO”

นำตัวจัดการ @WebSocketGateway ห้อง และฮุกวงจรชีวิตไปใช้งานสำหรับการสื่อสารแบบสด คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “เกตเวย์ WebSocket ด้วยอะแดปเตอร์ Socket.IO” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม

ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เกตเวย์ WebSocket ด้วยอะแดปเตอร์ Socket.IO
  2. การยืนยันตัวตนและการป้องกันการเชื่อมต่อซ็อกเก็ต
  3. เหตุการณ์ที่เซิร์ฟเวอร์ส่งสำหรับการพุชทางเดียว
  4. การปรับขนาดระบบเรียลไทม์ด้วยอะแดปเตอร์ Redis Pub/Sub
← กลับไปที่ NestJS Enterprise Backend APIs