728x90
반응형
728x170

안녕하세요. 오늘은 Nest에서 Websocket을 구현하려 할 때 어떻게 하는 지 포스팅해보겠습니다.

웹소켓은 Nest에서만 다루는 개념이 아니기 때문에 따로 웹소켓이 무엇인지 여기에서 다루진 않겠습니다.
웹소켓에 대해 궁금하시다면 아래 부분을 참고하고 보시면 됩니다.

 

[바미] WebSocket과 Socket.io차이는 무엇일까?

들어가기전에.. Socket.io와 WebSocket 모두 실시간 양방향 통신을 가능하게 하는 기술인데요. 지금 다니는 회사에서는 Socket.io를 주로 사용하고 있어요. 처음 Socket.io를 공부할 때 WebSocket에 대해 먼저

codesk.tistory.com

 


구현

WebSocket 모듈 설치

WebSocket 통신을 쉽게 구현할 수 있도록 @nestjs/websockets 모듈과 Socket.IO 또는 WS 라이브러리를 사용한 통합을 제공하는데 이번에는 Socket.IO를 사용하여 구현해보도록 하겠습니다.

 

먼저, @nestjs/websockets 모듈과 Socket.IO 라이브러리를 프로젝트에 추가해주세요.

npm install @nestjs/websockets socket.io

 

WebSocket 게이트웨이 생성

그 다음엔 WebSocket 통신을 관리하기 위해 게이트웨이를 생성해주어야 합니다.

게이트웨이는 특정 경로나 네임스페이스에 대한 WebSocket 연결을 처리하는 역할을 하죠.

nest generate gateway events

 

이렇게 하면 events.gateway.ts 파일을 생성하고, 이 파일 안에 EventsGateway 클래스를 정의돼요.

EventsGateway 구현

클라이언트와의 연결, 메시지 수신, 메시지 발송 등의 로직을 EventsGateway 클래스에 구현해봅시다!

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

@WebSocketGateway()
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}`);
  }

  @SubscribeMessage('message')
  handleMessage(client: Socket, payload: any): void {
    this.server.emit('message', payload);
  }
}

클라이언트의 연결과 연결 해제를 로깅하고, message 이벤트를 수신하여 모든 클라이언트에게 메시지를 전송하도록 만들어 봤습니다.

 

등록

이제 이 부분을 app.module.ts에 등록해보죠.

import { Module } from '@nestjs/common';
import { EventsGateway } from './events/events.gateway';

@Module({
  imports: [],
  controllers: [],
  providers: [EventsGateway], // EventsGateway를 providers 배열에 추가
})
export class AppModule {}

 

마지막으로 main.ts부분 입니다.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
  console.log(`Application is running on: ${await app.getUrl()}`);
}

bootstrap();

클라이언트 측 구현

이제 클라이언트가 남았네요. 클라이언트 부분을 구현해봅시다.

index.html로 추가해봅시다.

<!DOCTYPE html>
<html>
<head>
    <title>Socket.IO and NestJS Example</title>
    <script src="/socket.io/socket.io.js"></script>
</head>
<body>
    <h2>Socket.IO with NestJS</h2>
    <script>
        const socket = io('http://localhost:3000');

        socket.on('connect', function () {
            console.log('Connected to server');
        });

        socket.on('message', function (data) {
            console.log('New message:', data);
        });

        // 서버에 메시지 보내기
        socket.emit('message', { user: 'User', message: 'Hello World' });
    </script>
</body>
</html>

 

이제 구현이 끝났습니다. 지금까지의 프로젝트 구조는 아래와 같습니다.

(HTML 파일은 추가로 넣지 않았어요)

my-nest-app/
├── src/
│   ├── events/
│   │   └── events.gateway.ts  # WebSocket 게이트웨이 구현
│   ├── app.module.ts          # 애플리케이션의 루트 모듈
│   └── main.ts                # 애플리케이션의 엔트리 포인트
├── node_modules/              # npm 패키지 디렉토리
├── package.json               # 프로젝트 메타데이터 및 의존성 정의
└── tsconfig.json              # TypeScript 컴파일러 설정

오늘은 NestJS에서 WebSocket을 사용하여 간단한 실시간 기능을 갖춘 애플리케이션을 만들어 보았습니다.

Nest에서는 @nestjs/websockets 모듈과 게이트웨이 클래스를 사용하여 서버 측에서의 WebSocket 로직을 관리할 수 있고, 클라이언트 측에서는 Socket.IO 라이브러리를 통해 서버와의 통신을 구현할 수 있어요.

 

WebSocket을 통해 실시간 채팅 외에도, 실시간 데이터 스트리밍 서비스 등을 구현할 수 있어 웹소켓을 Nest로 구현하셔야 할 때 참고가 되셨길 바랍니다.

 

 

 

728x90
반응형
그리드형
Bami