[NestJS] chat service

Younghwan Cha·2023년 2월 28일
0

Nest.js

목록 보기
6/27
post-thumbnail
npm i --save @nestjs/websockets @nestjs/platform-socket.io
npm i -D @types/socket.io

websocket server 를 위해서는 두가지 작업이 필요하다

  1. EventsGateway module
  2. main.ts 에 webSocketAdapter 추가

EventsGateway module

@WebSocketGateway(8080)
export class EventGateway {
  @WebSocketServer()
  server: Server

  @SubscribeMessage('connect')
  onConnect(client: any, dat: any, mets: any) {
    console.log(this.server.clients);
    
    this.server.clients.forEach(client => {
      client.send(JSON.stringify({
        type: 'notification',
        msg: `새로운 유저가 접속하였습니다. ${this.server.clients.size}`
      }))
    })

    return 'websocket connection made';
  }

  @SubscribeMessage('event')
  onEvent(client: any, data: any) {
    console.log(data);
    
    this.server.clients.forEach(client => {
      client.send(JSON.stringify({
        type: 'chat',
        msg: data
      }))
    })

    return 'hello world';
  }
}
  • @WebSocketGateway
    해당 데코레이터를 통해 Socket Server를 세팅한다.
  • @SubscribeMessage('event')
    event 라는 유형의 message 를 받게되면 onEvent 함수를 동작시킨다

main.ts

import { NestFactory } from '@nestjs/core';
import { WsAdapter } from '@nestjs/platform-ws';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useWebSocketAdapter(new WsAdapter(app));

  await app.listen(3000);
  console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
  • app.useWebSocketAdapter(new WsAdapter(app));

[nestjs socket] https://docs.nestjs.com/websockets/gateways#lifecycle-hooks
[nestjs websocket] https://blog.ewq.kr/m/37

profile
개발 기록

0개의 댓글