nestjs webSocket

agnusdei·2023년 10월 16일

Angular와 NestJS를 함께 사용하여 WebSocket을 구현하는 방법에 대한 상세한 설명을 제공하겠습니다. WebSocket은 실시간 양방향 통신을 가능하게 하는 프로토콜이며, Angular와 NestJS는 WebSocket을 구현하고 통신하는데 사용될 것입니다.

  1. NestJS 프로젝트 생성:

    NestJS 백엔드 서버를 먼저 생성합니다. 아래 명령어를 통해 NestJS 프로젝트를 생성합니다.

    npx @nestjs/cli new nest-websocket-app
  2. 프로젝트 디렉토리로 이동:

    생성된 프로젝트 디렉토리로 이동합니다.

    cd nest-websocket-app
  3. NestJS WebSocket 모듈 설치:

    WebSocket을 사용하기 위해 @nestjs/websockets 패키지를 설치합니다.

    npm install --save @nestjs/websockets
  4. WebSocket 모듈 생성:

    NestJS WebSocket 모듈을 생성합니다.

    nest generate module websocket

    생성된 websocket.module.ts 파일을 열고 다음과 같이 수정합니다:

    import { Module } from '@nestjs/common';
    import { WebsocketGateway } from './websocket.gateway';
    
    @Module({
      providers: [WebsocketGateway],
    })
    export class WebsocketModule {}
  5. WebSocket Gateway 생성:

    WebSocketGateway를 생성하고 WebSocket 이벤트를 처리합니다.

    nest generate gateway websocket

    생성된 websocket.gateway.ts 파일을 열고 다음과 같이 수정합니다:

    import {
      WebSocketGateway,
      OnGatewayInit,
      OnGatewayConnection,
      OnGatewayDisconnect,
    } from '@nestjs/websockets';
    import { Socket, Server } from 'socket.io';
    
    @WebSocketGateway()
    export class WebsocketGateway
      implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
    {
      private server: Server;
    
      afterInit(server: Server) {
        this.server = server;
      }
    
      handleConnection(client: Socket) {
        // 클라이언트 연결 시 실행되는 코드
      }
    
      handleDisconnect(client: Socket) {
        // 클라이언트 연결 해제 시 실행되는 코드
      }
    }
  6. WebSocket 모듈 연결:

    메인 애플리케이션 모듈(app.module.ts)에서 WebSocket 모듈을 가져오고 WebsocketModule을 imports 배열에 추가합니다.

    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { WebsocketModule } from './websocket/websocket.module';
    
    @Module({
      imports: [WebsocketModule],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}
  7. Angular 프로젝트 생성:

    이제 Angular 프론트엔드 앱을 생성합니다.

    ng new angular-websocket-app
  8. WebSocket 클라이언트 설정:

    Angular 앱에서 WebSocket을 사용하기 위해 socket.io-client 패키지를 설치합니다.

    npm install socket.io-client --save

    Angular 앱에서 WebSocket 서버와 통신할 수 있는 서비스를 생성하고 설정합니다.

    // websocket.service.ts
    
    import { Injectable } from '@angular/core';
    import { io, Socket } from 'socket.io-client';
    
    @Injectable({
      providedIn: 'root',
    })
    export class WebsocketService {
      private socket: Socket;
    
      constructor() {
        this.socket = io('http://localhost:3000'); // NestJS 백엔드 서버 주소로 변경
      }
    
      sendMessage(message: string) {
        this.socket.emit('chatMessage', message);
      }
    
      // 다른 WebSocket 이벤트 핸들링 메서드도 추가할 수 있습니다.
    }
  9. Angular 컴포넌트에서 WebSocket 사용:

    Angular 컴포넌트에서 WebSocket 서비스를 주입하고 사용할 수 있습니다.

    // app.component.ts
    
    import { Component } from '@angular/core';
    import { WebsocketService } from './websocket.service';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css',
    })
    export class AppComponent {
      message: string = '';
    
      constructor(private websocketService: WebsocketService) {}
    
      sendMessage() {
        this.websocketService.sendMessage(this.message);
      }
    }
  10. Angular 컴포넌트 템플릿 수정:

    Angular 컴포넌트 템플릿에서 WebSocket을 통해 메시지를 보내거나 표시할 수 있습니다.

    <!-- app.component.html -->
    
    <input [(ngModel)]="message" placeholder="Type a message" />
    <button (click)="sendMessage()">Send</button>

이제 NestJS 백엔드와 Angular 프론트엔드 간에 WebSocket 통신이 설정되었습니다. 클라이언트에서 메시지를 보내고 서버에서 WebSocket 이벤트를 처리하려면 WebSocket 서비스와 Angular 컴포넌트를 사용할 수 있습니다. 서버 측에서도 WebSocketGateway를 사용하여 이벤트를 처리할 수 있습니다.

0개의 댓글