0Pricing
Node.js Backend Development Bootcamp · 강의

게이트웨이 구성

NestJS에서 WebSocket 게이트웨이를 구성하고 연결 이벤트, 메시지, 방 관리를 처리합니다.

게이트웨이 구성은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 6개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Node.js Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Node.js Backend Development Bootcamp 강의에는 총 6개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Unlocking Real-time with Gateways

Welcome back! In the previous lesson, we learned about WebSockets. Now, let's dive into how NestJS makes real-time communication easy with Gateways.

Think of a Gateway as a special controller for WebSocket connections. It listens for messages from clients and sends responses back, enabling dynamic, two-way communication.

Creating Your First Gateway

To create a Gateway, we use the @WebSocketGateway() decorator. This decorator marks a class as a WebSocket gateway.

By default, NestJS uses Socket.IO. You can specify a port, namespace, or other options. Let's start with a basic gateway:

import { WebSocketGateway,
         WebSocketServer } from '@nestjs/websockets';
import { Server } from 'socket.io';

// src/events.gateway.ts
@WebSocketGateway(3001) // Listens on port 3001 for WS
export class EventsGateway {
  @WebSocketServer() server: Server;
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000); // HTTP app, WS runs alongside
}
bootstrap();

Gateway Configuration Options

The @WebSocketGateway() decorator accepts an optional configuration object. This lets you customize how your WebSocket server behaves:

  • port: The port the WebSocket server listens on (e.g., 3001).
  • namespace: Group connections under a specific path (e.g., '/chat').
  • cors: Configure Cross-Origin Resource Sharing for browser clients.
  • adapter: Specify a custom WebSocket adapter (e.g., for `ws` instead of `socket.io`).

Handling Connections & Disconnections

Gateways can react to client connections and disconnections using lifecycle hooks. These are interfaces your gateway can implement:

  • OnGatewayInit: Called once the gateway is initialized.
  • OnGatewayConnection: Called when a client connects.
  • OnGatewayDisconnect: Called when a client disconnects.

Use these to perform setup or cleanup tasks.

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

// src/events.gateway.ts
@WebSocketGateway(3001)
export class EventsGateway
  implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;

  handleConnection(client: Socket, ...args: any[]) {
    console.log(`Client connected: ${client.id}`);
  }

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

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Subscribing to Client Messages

Clients send messages with an 'event name'. Your gateway listens for these specific events using the @SubscribeMessage() decorator.

The decorated method receives the client (Socket instance) and the payload (data sent by the client).

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

// src/events.gateway.ts
@WebSocketGateway(3001)
export class EventsGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('sendMessage')
  handleMessage(client: Socket, payload: string): void {
    console.log(`Message from ${client.id}: ${payload}`);
    // Process payload, then send response
  }
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Sending Messages Back to Clients

Once your gateway receives a message, you'll often want to send a response. You can inject the WebSocketServer instance using @WebSocketServer().

To send a message to a specific client, use client.emit('eventName', data). To broadcast to all clients, use this.server.emit('eventName', data).

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

// src/events.gateway.ts
@WebSocketGateway(3001)
export class EventsGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('echo')
  handleEcho(client: Socket, payload: string): void {
    console.log(`Received: ${payload} from ${client.id}`);
    client.emit('echoResponse', `You said: ${payload}`);
  }

  @SubscribeMessage('broadcast')
  handleBroadcast(client: Socket, payload: string): void {
    this.server.emit(
      'broadcastMessage', 
      `${client.id} broadcasted: ${payload}`
    );
  }
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Organizing Clients with Rooms

For more complex applications, you might not want to broadcast every message to every client. This is where rooms come in handy!

Rooms allow you to group specific clients together. Messages can then be sent only to clients within a particular room. This is perfect for chat channels, game lobbies, or specific user notifications.

Joining and Leaving Rooms

Socket.IO clients can join or leave rooms dynamically. You can manage this from your gateway methods using the client instance:

  • client.join(roomName): Adds the client to the specified room.
  • client.leave(roomName): Removes the client from the specified room.

A client can be in multiple rooms simultaneously.

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

// src/events.gateway.ts
@WebSocketGateway(3001)
export class EventsGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('joinRoom')
  handleJoinRoom(client: Socket, room: string): void {
    client.join(room);
    client.emit('joinedRoom', `You joined ${room}`);
    console.log(`${client.id} joined room: ${room}`);
  }

  @SubscribeMessage('leaveRoom')
  handleLeaveRoom(client: Socket, room: string): void {
    client.leave(room);
    client.emit('leftRoom', `You left ${room}`);
    console.log(`${client.id} left room: ${room}`);
  }
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Sending Messages to Specific Rooms

Once clients are in rooms, you can send targeted messages. Use the server.to(roomName).emit('eventName', data) method.

This ensures only clients subscribed to that particular room receive the message, making your real-time updates efficient and relevant.

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

// src/events.gateway.ts
@WebSocketGateway(3001)
export class EventsGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('roomMessage')
  handleRoomMessage(
    client: Socket,
    payload: { room: string; message: string },
  ): void {
    const { room, message } = payload;
    this.server
      .to(room)
      .emit('roomUpdate',
            `[${room}] ${client.id}: ${message}`);
    console.log(
      `Message in ${room} from ${client.id}: ${message}`
    );
  }
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Gateway Configuration Quiz

Which of the following statements about NestJS WebSocket Gateways and rooms are TRUE?

Recap: Master Your Gateway

Great job! You've learned how to configure NestJS Gateways for powerful real-time communication.

  • We defined gateways using @WebSocketGateway().
  • We explored configuration options like port and namespace.
  • We implemented lifecycle hooks for connections and disconnections.
  • We handled client messages with @SubscribeMessage().
  • We used @WebSocketServer() to broadcast and send targeted messages.
  • Finally, we mastered rooms for efficient client grouping and targeted messaging.

Next, we'll build a full real-time chat application!

자주 묻는 질문

“게이트웨이 구성” 강의는 무료인가요?

네 — “게이트웨이 구성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 6개의 강의가 포함되어 있습니다.

“게이트웨이 구성”에서 뭘 배우나요?

NestJS에서 WebSocket 게이트웨이를 구성하고 연결 이벤트, 메시지, 방 관리를 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 4번째 강의입니다.

“게이트웨이 구성” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. WebSockets 입문
  2. NestJS를 사용한 WebSockets
  3. Node.js에서 Socket.IO 구현하기
  4. 게이트웨이 구성
  5. 실시간 채팅 애플리케이션 만들기
  6. 실시간 채팅 애플리케이션
← Node.js Backend Development Bootcamp(으)로 돌아가기