NestJS를 사용한 WebSockets
WebSockets의 기본 개념과 NestJS가 실시간 양방향 통신을 강력하게 지원하는 방식을 이해합니다.
NestJS를 사용한 WebSockets은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 6개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Node.js Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Node.js Backend Development Bootcamp 강의에는 총 6개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Unlock Real-time Communication
Ever wondered how chat apps, live sports scores, or multiplayer games update instantly? This is real-time communication!
Traditional web requests are like a quick phone call: you ask, you get an answer, then hang up. For constant updates, we need something more persistent.
WebSockets provide this 'always-on' connection, allowing data to flow freely between server and client without constant re-requests.
HTTP's Limitations vs. WS
Let's compare how HTTP and WebSockets handle communication:
- HTTP: A request-response protocol. The client sends a request, the server sends a response, and the connection closes. Inefficient for continuous, bidirectional updates.
- WebSockets: A persistent, bidirectional communication protocol. Once connected, both client and server can send data at any time without re-establishing the connection.
Think of HTTP as mailing a letter, and WebSockets as an open phone line.
How a WS Connection Starts
A WebSocket connection doesn't just appear. It begins with a special HTTP request called a handshake:
- The client sends an HTTP request with an 'Upgrade' header, asking to switch protocols.
- If the server supports WebSockets, it responds with an 'Upgrade' header confirming the switch.
- This 'upgrades' the connection from HTTP to the WebSocket protocol (
ws://orwss://for secure).
After the handshake, the raw TCP connection is used for full-duplex WebSocket messages.
NestJS & WebSockets Module
Building WebSocket servers from scratch can be complex. NestJS simplifies this with its robust WebSocket module.
It provides powerful abstractions like Gateways that integrate seamlessly with its modular architecture, letting you focus on your application logic rather than low-level connection management.
NestJS supports various underlying WebSocket libraries, with @nestjs/platform-ws being a common and easy-to-use choice.
Understanding NestJS Gateways
In NestJS, a Gateway is a class decorated with @WebSocketGateway(). It acts as the primary entry point for WebSocket connections, similar to how a Controller handles HTTP requests.
Gateways listen for incoming WebSocket events (messages from clients) and can also emit events back to connected clients. They are central to managing real-time interactions in your NestJS application.
Basic Node.js WS Server
Let's see a simple WebSocket server using the ws library in Node.js. This demonstrates the core idea of listening for connections and messages, which NestJS abstracts for us.
Run this example and observe the console output when a client connects. (You can connect using new WebSocket('ws://localhost:8080') in a browser's console).
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
console.log('Client connected!');
ws.on('message', message => {
console.log(`Received: ${message}`);
ws.send(`Echo: ${message}`);
});
ws.on('close', () => console.log('Client disconnected.'));
});
console.log('WebSocket server started on port 8080');Building a NestJS Gateway
To create a Gateway in NestJS, you define a class and decorate it with @WebSocketGateway(). This decorator can take an optional port and options for the underlying WebSocket server.
Here's a basic structure for a chat gateway:
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Server } from 'socket.io'; // Or 'ws' Server type
@WebSocketGateway(8080, { cors: true }) // Listens on port 8080
export class ChatGateway {
@WebSocketServer()
server: Server; // Inject the WebSocket server instance
// Gateway logic will go here
}Handling Messages with Decorators
NestJS Gateways use decorators to handle specific incoming messages (events) from clients.
@SubscribeMessage('eventName'): Marks a method to handle messages with a specific name.@MessageBody(): Extracts the data payload from the incoming message.@ConnectedSocket(): Extracts the connected client's socket instance.
This makes it easy to route and process client messages.
import { SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets';
import { Socket } from 'socket.io'; // Or 'ws' Socket type
// ... inside ChatGateway class
@SubscribeMessage('sendMessage')
handleMessage(
@MessageBody() data: string,
@ConnectedSocket() client: Socket,
): string {
console.log(`Client ${client.id} sent: ${data}`);
client.emit('messageReceived', `You said: ${data}`);
return data; // Can also return observable or promise
}Managing Connections Lifecycle
Gateways can also manage connection and disconnection events by implementing lifecycle interfaces:
OnGatewayConnection: For logic when a client connects.OnGatewayDisconnect: For logic when a client disconnects.OnGatewayInit: For initialization tasks when the gateway is ready.
These methods give you control over the client's journey.
import { OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit } from '@nestjs/websockets';
import { Socket } from 'socket.io';
// ... inside ChatGateway class
export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
afterInit(server: any) {
console.log('Gateway Initialized!');
}
handleConnection(client: Socket, ...args: any[]) {
console.log(`Client connected: ${client.id}`);
}
handleDisconnect(client: Socket) {
console.log(`Client disconnected: ${client.id}`);
}
}Sending Data to Clients
Once you have the server instance (injected with @WebSocketServer()) or a specific client socket, you can send messages:
client.emit('event', data): Sends data to a specific client.this.server.emit('event', data): Broadcasts data to all connected clients.this.server.to('roomName').emit('event', data): Sends data to clients in a specific 'room' (useful for group chats).
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
// ... inside ChatGateway class
@SubscribeMessage('joinRoom')
handleJoinRoom(@MessageBody() room: string, @ConnectedSocket() client: Socket) {
client.join(room);
client.emit('joinedRoom', `You joined ${room}`);
this.server.to(room).emit('roomMessage', `${client.id} joined ${room}`);
}
@SubscribeMessage('broadcastMessage')
handleBroadcast(@MessageBody() message: string) {
this.server.emit('newMessage', `Broadcast: ${message}`);
}Quick Check: WS Features
Which of the following are key characteristics of WebSocket communication?
Recap: WebSockets with NestJS
In this lesson, we explored the fundamentals of WebSockets and their powerful integration with NestJS.
- WebSockets provide persistent, bidirectional communication for real-time applications.
- NestJS simplifies WebSocket development through Gateways.
- Gateways use decorators like
@WebSocketGateway(),@SubscribeMessage(),@MessageBody(), and lifecycle hooks to manage events and connections. - You can send messages to individual clients or broadcast to many using the injected
Serverinstance.
Next, we'll dive deeper into configuring Gateways and handling more complex scenarios.
자주 묻는 질문
“NestJS를 사용한 WebSockets” 강의는 무료인가요?
네 — “NestJS를 사용한 WebSockets” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 6개의 강의가 포함되어 있습니다.
“NestJS를 사용한 WebSockets”에서 뭘 배우나요?
WebSockets의 기본 개념과 NestJS가 실시간 양방향 통신을 강력하게 지원하는 방식을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 2번째 강의입니다.
“NestJS를 사용한 WebSockets” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- WebSockets 입문
- NestJS를 사용한 WebSockets
- Node.js에서 Socket.IO 구현하기
- 게이트웨이 구성
- 실시간 채팅 애플리케이션 만들기
- 실시간 채팅 애플리케이션