在前面的章節中,我們設計的 API 大多基於 HTTP Request/Response 模式,這種方式雖然直觀,但在某些需要「即時性」的場景中,效率就顯得不足,例如:
特性 | HTTP API | WebSocket |
---|---|---|
通訊模式 | 單向:Client 發送請求 → Server 回應 | 雙向:Client 與 Server 都能主動發送 |
連線 | 每次請求需要建立連線 | 連線建立後可持續存在 |
適用場景 | RESTful API、CRUD 操作 | 即時性應用(聊天室、即時推播) |
簡單來說:
我們使用 Node.js + ws 套件 來示範。
npm install ws
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws) => {
console.log("Client connected");
// 接收來自 client 的訊息
ws.on("message", (message) => {
console.log(`Received: ${message}`);
ws.send(`伺服器回覆: ${message}`);
});
// 客戶端斷線
ws.on("close", () => {
console.log("Client disconnected");
});
});
console.log("WebSocket Server is running on ws://localhost:8080");
可以直接在瀏覽器 Console 測試:
const socket = new WebSocket("ws://localhost:8080");
// 連線成功
socket.onopen = () => {
console.log("Connected to server");
socket.send("Hello from client!");
};
// 接收訊息
socket.onmessage = (event) => {
console.log("Message from server:", event.data);
};
使用 WebSocket 可以讓使用者即時收到其他人發送的訊息。
例如電商平台的「訂單狀態更新」即時推播。
遊戲角色位置、血量等資訊需要即時同步。
股票報價、匯率、加密貨幣價格的即時更新。
實際專案中,WebSocket 與 REST API 常常搭配使用:
WebSocket 為 API 帶來了「即時性」,突破了傳統 HTTP 的單向限制。