종속성 설치:
먼저, 웹소켓을 Nest 애플리케이션에 통합하려면 @nestjs/websockets
와 @nestjs/platform-socket.io
패키지를 설치해야 합니다.
$ npm install @nestjs/websockets @nestjs/platform-socket.io --save
WebSocket Gateway 생성:
Nest 애플리케이션에서 WebSocket을 사용하기 위해 WebSocketGateway를 생성해야 합니다. WebSocketGateway는 웹소켓과 관련된 기능들을 처리하는 클래스입니다.
// chat.gateway.ts
import { WebSocketGateway, WebSocketServer, OnGatewayConnection, OnGatewayDisconnect, SubscribeMessage, MessageBody } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
@WebSocketGateway()
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server: Server;
// 클라이언트가 웹소켓에 연결되면 호출됩니다.
handleConnection(client: Socket) {
console.log(`Client connected: ${client.id}`);
this.server.emit('connectedUsers', this.getConnectedUsers());
}
// 클라이언트가 웹소켓 접속을 해제하면 호출됩니다.
handleDisconnect(client: Socket) {
console.log(`Client disconnected: ${client.id}`);
this.server.emit('connectedUsers', this.getConnectedUsers());
}
// 연결된 클라이언트 수를 반환하는 메서드
private getConnectedUsers(): number {
return this.server.engine.clientsCount;
}
// 클라이언트로부터 'chatMessage' 이벤트를 구독하는 메서드
@SubscribeMessage('chatMessage')
handleChatMessage(@MessageBody() message: string): void {
this.server.emit('chatMessage', message); // 모든 클라이언트에게 채팅 메시지를 브로드캐스팅합니다.
}
}
AppModule 설정:
AppModule에서 WebSocketGateway를 프로바이더로 등록하여 사용할 수 있도록 설정합니다.
// app.module.ts
import { Module } from '@nestjs/common';
import { ChatGateway } from './chat.gateway';
@Module({
imports: [],
controllers: [],
providers: [ChatGateway], // ChatGateway를 Nest 애플리케이션의 프로바이더로 등록합니다.
})
export class AppModule {}
웹소켓 클라이언트 예시:
웹소켓 클라이언트를 생성하여 웹 브라우저에서 실행할 수 있습니다. 다음은 간단한 HTML과 JavaScript를 사용한 웹소켓 클라이언트 예시입니다.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Example</title>
</head>
<body>
<input type="text" id="messageInput" placeholder="Type your message">
<button onclick="sendMessage()">Send</button>
<div id="messages"></div>
<script src="/socket.io/socket.io.js"></script> <!-- socket.io 클라이언트 라이브러리를 로드합니다. -->
<script>
const socket = io('http://localhost:3000'); // Nest 서버 주소에 맞게 변경해주세요
socket.on('chatMessage', (message) => {
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML += `<p>${message}</p>`;
});
socket.on('connectedUsers', (count) => {
console.log(`Connected users: ${count}`);
});
function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value;
socket.emit('chatMessage', message);
input.value = '';
}
</script>
</body>
</html>
위와 같이 설정하면, Nest 애플리케이션에서 웹소켓을 사용하는 예시가 구현됩니다. 웹소켓 클라이언트를 실행하면 웹 브라우저에서 웹소켓 서버와 실시간으로 통신할 수 있습니다. ChatGateway
를 사용하여 서버에서 chatMessage
이벤트를 처리하고, 클라이언트와 서버 사이에서 실시간 통신을 구현할 수 있습니다.