Hướng dẫn thử thách
1 / 1
WebSockets Review
## WebSockets vs HTTP
- **HTTP** follows a request-response model: the client sends a request, the server sends a response, then the connection closes.
- **WebSockets** create a permanent, bidirectional connection between a client and a server that stays open until either side sends a closing signal.
- HTTP is well-suited for loading pages or fetching data, but becomes slow and inefficient for real-time applications.
- Every WebSocket connection begins with an **HTTP handshake**: the client requests an upgrade, and the server responds with `101 Switching Protocols`.
### WebSocket connection flow
1. Client connects to server via HTTP and requests an upgrade.
2. Server accepts and responds with `101 Switching Protocols`.
3. Connection stays open.
4. Both sides exchange data at any time until the connection closes.
### HTTP vs WebSocket communication
- **HTTP**: `Client → Request → Server → Response` (one cycle, then closes)
- **WebSocket**: `Client ↔ Server` (persistent, bidirectional)
### A helpful analogy
- **HTTP** is like exchanging letters: you write one, wait for a reply, and the conversation ends.
- **WebSockets** are like a phone call: both sides talk in real time for as long as needed.
### Real-world uses of WebSockets
- Chat applications
- Online multiplayer games
- Live sports score updates
- Stock market dashboards
- Collaborative tools (e.g. Google Docs)
## Pub/Sub Architecture
- **Pub/Sub** (Publish/Subscribe) is a messaging architecture that allows parts of a system to communicate without knowing about each other directly.
- There are three main parts: **publishers**, **topics**, and **subscribers**.
- A **publisher** sends messages to a topic.
- A **topic** (also called a channel or group) acts as the middleman.
- A **subscriber** receives messages from topics it has subscribed to.
### Pub/Sub message flow
1. A subscriber subscribes to a topic.
2. A publisher sends a message to that topic.
3. The messaging system delivers the message to every subscriber of that topic.
### Direct communication vs Pub/Sub
- **Without Pub/Sub**: `Application A → Application B` — tightly coupled; a change in B can break A.
- **With Pub/Sub**: `Application A → Topic → Subscribers` — A only publishes; it doesn't need to know who receives.
### Real-world uses of Pub/Sub
- Chat applications with multiple rooms
- Online multiplayer games
- Notification systems
- Live dashboards
- Event-driven applications
### WebSockets vs Pub/Sub
- **WebSockets** provide the communication channel (the road).
- **Pub/Sub** provides the messaging pattern that determines who receives specific messages (the traffic system).
- Many real-time applications use both together: WebSockets keep the connection open, while Pub/Sub routes messages to the right subscribers.
## Working with WebSockets in Node.js
- Node.js has no built-in WebSocket server. The `ws` library is the standard external package used for this.
- Install with: `npm install ws`
### Creating a WebSocket server
```js
const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 3000 });
```
### WebSocket events
| Event | Trigger |
|---|---|
| `connection` | A new client connects to the server |
| `message` | A connected client sends data |
| `close` | A connection closes |
| `error` | Something goes wrong on the connection |
### Sending a message to a client
```js
socket.send("Hello from the server");
```
### Broadcasting to all connected clients
- `server.clients` holds all connected clients.
- Check `readyState === WebSocket.OPEN` before sending to avoid errors with disconnected clients.
```js
server.on("connection", (socket) => {
socket.on("message", (message) => {
server.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message.toString());
}
});
});
});
```
- **Broadcasting** is the pattern of sending a message to multiple connected clients at once — used in chat apps, live notifications, sports updates, and multiplayer game events.
Nhiệm vụ của bạn
Review the WebSockets topics and concepts.
Vượt qua bài kiểm tra hiện tại để mở khóa bài tiếp theo.
main.sh
UTF-8 • Tab Size: 2Kiểm tra bài:⌘↵