Nest.js를 배워보자/11. NestJS WebSocket 실전 — 실시간 시스템 만들기

NestJS WebSocket Gateway 기본 설정

_Blue_Sky_ 2025. 12. 3. 11:07
728x90

NestJS에서 실시간 시스템을 구축하는 핵심은 @WebSocketGateway() 데코레이터가 적용된 Gateway 클래스입니다. 이 클래스는 WebSocket 서버의 동작을 정의하고, 클라이언트의 연결 및 메시지 이벤트를 처리합니다.

1. Gateway 클래스 기본 설정

NestJS CLI를 사용해 게이트웨이를 생성하거나 직접 파일을 만듭니다.

# NestJS CLI로 생성
nest g gateway chat

기본적인 Gateway 클래스 설정은 다음과 같습니다.

728x90
// src/chat/chat.gateway.ts
import {
  WebSocketGateway,
  SubscribeMessage,
  MessageBody,
  ConnectedSocket,
  WsResponse,
  OnGatewayInit,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Logger } from '@nestjs/common';
import { Server, Socket } from 'socket.io'; // 일반적으로 socket.io를 사용합니다.

@WebSocketGateway(
  8080, // 1. 포트 번호 (선택 사항, 기본 HTTP 서버 포트와 다를 수 있음)
  {
    namespace: '/chat', // 2. 네임스페이스 지정
    cors: {
      origin: '*', // 3. CORS 설정
    },
  },
)
export class ChatGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  private readonly logger = new Logger(ChatGateway.name);
  private server: Server;

  // 4. 서버 인스턴스 초기화 (afterInit)
  afterInit(server: Server) {
    this.server = server;
    this.logger.log('WebSocket Gateway 초기화 완료.');
  }

  // 5. 클라이언트 연결 처리 (handleConnection)
  handleConnection(client: Socket, ...args: any[]) {
    this.logger.log(`클라이언트 연결: ${client.id}`);
    // 연결 시 특정 방에 자동으로 참가시키거나 초기 데이터를 전송할 수 있습니다.
  }

  // 6. 클라이언트 연결 해제 처리 (handleDisconnect)
  handleDisconnect(client: Socket) {
    this.logger.log(`클라이언트 연결 해제: ${client.id}`);
  }

  // 7. 특정 메시지 이벤트 구독 (SubscribeMessage)
  @SubscribeMessage('sendMessage')
  handleMessage(
    @MessageBody() data: string,
    @ConnectedSocket() client: Socket,
  ): void {
    this.logger.log(`메시지 수신 (${client.id}): ${data}`);
    // 클라이언트 자신을 제외한 모두에게 메시지를 브로드캐스팅
    client.broadcast.emit('receiveMessage', { user: client.id, message: data });
  }

  // 선택 사항: 특정 응답 형식으로 반환
  @SubscribeMessage('ping')
  handlePing(): WsResponse<string> {
    return { event: 'pong', data: 'Server is Alive!' };
  }
}

2. @WebSocketGateway() 데코레이터 옵션 상세

옵션 설명 베스트 프랙티스
port (첫 번째 인자) Gateway가 수신할 포트. 생략 시 메인 HTTP 서버 포트를 사용합니다. HTTP 서버와 포트를 분리하려면 명시합니다.
namespace 네임스페이스를 정의하여 여러 게이트웨이 또는 서비스 분리 (예: /chat, /notifications). 서비스별로 분리하여 트래픽 관리를 용이하게 합니다.
cors 클라이언트의 접속을 허용할 CORS 설정입니다. origin을 구체적으로 지정하거나 배포 환경 변수를 사용합니다.
transports WebSocket 연결에 사용할 전송 방식 (예: ['websocket', 'polling']). 기본 설정(모두 포함)이 보통 적절하지만, 특정 환경에 맞게 조정 가능합니다.

728x90

3. 모듈 등록

Gateway를 사용하려면 반드시 해당 모듈의 providers 배열에 등록해야 합니다.

// src/chat/chat.module.ts
import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway';

@Module({
  providers: [ChatGateway], // Gateway 등록
})
export class ChatModule {}

 

728x90