왜 WebSocket을 사용할까?
기존 HTTP 요청 / 응답 모델에서는 클라이언트가 서버에 요청을 보내고 서버가 응답하는 단방향 통신만 가능하다
이런 모델은 실시간으로 데이터를 교환하기 어렵고, 서버에서 클라이언트로 능동적으로 데이터를 보내는 것이 불가능하다.
이와 반면 WebSocket은 WebSocket의 연결이 유지되는한 서버나 클라이언트는 데이터 전송을 즉각적으로 할 수 있고 초기 헨드셰이크 이후 추가적인 HTTP 헤더 없이 순수 데이터만을 전송하기 때문에 HTTP 폴링(polling)이나 롱 폴링(logn-polling)에 비해 통신 오버헤드가 크게 줄어든다
NestJS로 실시간 채팅 애플리케이션을 구현하려면 WebSocket 을 사용하는 것이 일반적이라고 한다.
쉽게 구현할 수 있는 모듈과 socket.io 혹은 라이브러리를 사용하는 기능을 제공하는데 예시를 통해 채팅 애플리케이션을 구현해보자
프로젝트 생성
nest new [project-name]
먼저 NestJS 프로젝트를 생성해준다
루프 프로젝트에서 프론트엔드 / 백엔드를 구분해서 생성했고 최초 프로젝트 구조는 위 사진과 같다
패키지 설치
npm install @nestjs/websockets @nestjs/platform-socket.io socket.io socket.io-client
Socket.io 관련 패키지들을 설치해준다
게이트웨이 생성
nest generate gateway chat
실시간 채팅을 처리할 WebSocket 게이트웨이를 생성한다.
게이트웨이는 WebSocket 연결을 관리하는 클래스다
chat.gateway.ts 등의 파일들을 생성하는데 여기에 클라이언트와의 연결, 메시지 송수신 등을 처리하는 로직을 구현하면 된다.
Gateway 기본 세팅
chat.gateway.ts
import {
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
MessageBody,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Logger } from '@nestjs/common';
import { Server, Socket } from 'socket.io';
import { AddMessageDto } from './dto/add-message.dto';
@WebSocketGateway({ cors: { origin: '*' } })
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server: Server;
private logger = new Logger('ChatGateway');
@SubscribeMessage('chat')
// 클라이언트로부터 받은 메시지(payload)를 처리
handleMessage(@MessageBody() payload: AddMessageDto): AddMessageDto {
this.logger.log(`Message received: ${payload.author} - ${payload.body}`);
this.server.emit('chat', payload);
return payload;
}
handleConnection(socket: Socket) {
this.logger.log(`Socket connected: ${socket.id}`);
}
handleDisconnect(socket: Socket) {
this.logger.log(`Socket disconnected: ${socket.id}`);
}
}
@WebSocketGateway() : 클래스가 웹소켓 게이트웨이이고, 해당 포트에서 웹 소켓 서버를 시작
@WebSocketSever() : server 변수에 웹소켓 서버의 인스턴스를 주입, server 변수를 통해 서버에 접근하고 관리할 수 있음
@SubscribeMessage() : 'chat' 라는 이름의 메시지를 구독하는 핸들러 선언, 클라이언트가 'chat' 메시지를 서버에 보내면 핸들러가 호출
@handleConnection & handleDisconnect : 클라이언트가 연결되거나 끊어졌을 때 호출, 각각의 소켓 연결 / 해제 이벤트를 로깅
Logger : NestJS에서 제공하는 로깅 기능을 사용하여 서버의 상태나 이벤트를 콘솔에 기록
add-message.dts.ts
chat 폴더 하위에 dto 를 생성해준다.
export class AddMessageDto {
author: string;
body: string;
}
main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(4000);
}
bootstrap();
기본적인 서버 준비는 완료되었다
참고 자료
https://docs.nestjs.com/websockets/gateways
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea
docs.nestjs.com
https://levelup.gitconnected.com/build-a-real-time-chat-app-using-nestjs-d57da4d35793
'Language & Framework > Node.JS' 카테고리의 다른 글
[NestJS] Websocket을 활용한 실시간 채팅 구현 #3 - jwt (0) | 2024.04.10 |
---|---|
[NestJS] Websocket을 활용한 실시간 채팅 구현 #2 - 클라이언트 기본 설정 (0) | 2024.04.04 |
[NestJS] Serialize, ClassSerializerInterceptor - 직렬화 (0) | 2024.04.02 |
[NestJS] 프로젝트 시작하기 (0) | 2024.03.10 |
[Node.JS] Express, EJS를 활용한 웹 서버 사용하기 (0) | 2023.10.13 |