# 개요
기존 HTTP 요청/응답 방식으로는 실시간 페이지 업데이트가 불가능하다는 단점이 존재한다.
그렇기 때문에, 실시간적인 데이터가 필요한 경우, 보통 connection을 계속 유지할 수 있는 socket 기술이 사용되는데,
WebSocket 기술을 예시로 튜토리얼을 진행해보자.
The WebSocket API allows for event-based two-way communication between a browser and a server.
NestJS has support for web sockets built-in, which makes use of the popular socket.io package. This makes setting up communications using the WebSocket API in NestJS rather simple.
1. Creating the NestJS Server
First, we are going to create our NestJS server.
In order to use web sockets in your NestJS project, you will need to install the following package:
npm install --save @nestjs/websockets
nest g module <웹소켓통신을 관리할 모듈 이름 : chat>
create a new file to implement a @WebSocketGateway.
// 클라이언트와의 메시지 요약어 존재
@SubscribeMessage('메시지예약어') function() {...} : 개별 클라이언트-> ('메시지예약어', 데이터) -> 서버로 보내왔을 경우, 처리하는 로직
client.broadcast.emit('메시지예약어', 데이터) : 서버 -> ('메시지예약어', 데이터) -> 연결된 모든 클라이언트로 데이터 보내기
OnGatewayConnection and OnGatewayDisconnect을 옵션으로, implement 수행가능(선택)
handleConnection() handleDisconnect()을 구현해야함
create file <web소켓 통신관련 이름>.gateway.ts
import { WebSocketGateway, WebSocketServer, SubscribeMessage, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets'; @WebSocketGateway() export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect { @WebSocketServer() server; // We set up a member variable called server that is decorated with @WebSocketServer // which will give us access to the server instance. // We can then use this to trigger events and send data to connected clients. users: number = 0; async handleConnection(){ // A client has connected this.users++; // Notify connected clients of current users this.server.emit('users', this.users); } async handleDisconnect(){ // A client has disconnected this.users--; // Notify connected clients of current users this.server.emit('users', this.users); } @SubscribeMessage('chat') async onChat(client, message){ client.broadcast.emit('chat', message); } }
import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway';
@Module({
providers: [ ChatGateway ] // Provider로
})
export class ChatModule {}
# Client App 생성
1. npm install --save ngx-socket-io
// This package just implements socket.io in an Angular friendly way.
2. app.module.ts 상에 매핑
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://localhost:3000', options: {}}; // backend 웹소켓서버 base url ★
@NgModule({
...
imports: [
...
SocketIoModule.forRoot(config) // ★
],
...
})
export class AppModule {}
3. websocket 통신전용 서비스 생성
ng g service services/chat
import { Injectable } from '@angular/core'; import { Socket } from 'ngx-socket-io'; @Injectable({ providedIn: 'root' }) export class ChatService { constructor(private socket: Socket) { //★ socket 의존성 주입 } sendChat(message){ this.socket.emit('chat', message); // Client -> Server // 서버 서비스 내 @SubscribeMessage('chat')에서 처리 } receiveChat(){ //Callback 함수?(Listen & Do) // Observable 형식이라서, subscribe()하여 사용할 것 return this.socket.fromEvent('chat'); //Server -> Client } getUsers(){ //Callback 함수?(Listen & Do) // Observable 형식이라서, subscribe()하여 사용할 것
return this.socket.fromEvent('users'); //Server -> Client } }
4. 일반 컴포넌트에서 사용하기
export class HomePage implements OnInit { public users: number = 0; public message: string = ''; public messages: string[] = []; constructor(private chatService: ChatService){ //의존성 주입 } ngOnInit(){ this.chatService.receiveChat().subscribe((message: string) => { this.messages.push(message); }); this.chatService.getUsers().subscribe((users: number) => { this.users = users; }); } addChat(){ this.messages.push(this.message); this.chatService.sendChat(this.message); this.message = ''; } }
# 출처
https://www.joshmorony.com/creating-a-simple-live-chat-server-with-nestjs-websockets/
'[DEV] App Dev ∕ Web Back > Framework ∕ NestJS' 카테고리의 다른 글
[NestJS] google login tutorial (0) | 2022.04.05 |
---|---|
[배포] 윈도우 방화벽 포트 열기 (0) | 2020.11.18 |
NestJS : JWT 토큰/ Config / Pagination (0) | 2020.10.20 |
NestJs : Node.js Back-end 프레임워크 (0) | 2020.08.19 |
최근댓글