使用 NestJS 实现 WebSockets
理解 WebSockets 的基础,以及 NestJS 如何为实时双向通信提供强大支持。
使用 NestJS 实现 WebSockets 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 2 节课,共 6 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 6 节课。
「使用 NestJS 实现 WebSockets」这节课中我会学到什么?
理解 WebSockets 的基础,以及 NestJS 如何为实时双向通信提供强大支持。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 6 节。
「使用 NestJS 实现 WebSockets」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- WebSockets 入门
- 使用 NestJS 实现 WebSockets
- 在 Node.js 中实现 Socket.IO
- 网关配置
- 构建实时聊天应用
- 实时聊天应用程序