通过 WebSockets 实现请求-响应
学习使用 WebSocket 消息 ID 和确认机制,模拟传统请求-响应语义的技术。
通过 WebSockets 实现请求-响应 是 CoddyKit 上的免费 WebSockets & Realtime Systems Programming 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Realtime Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Beyond Fire-and-Forget
WebSockets are fantastic for real-time, continuous streams of data. Think chat messages, live updates, or game states!
But what if you need to perform a traditional request-response interaction, like fetching specific data from a server and expecting a single, matching reply?
The Asynchronous Nature
Unlike HTTP, where each request gets an immediate, direct response, WebSockets operate on an asynchronous, message-based model.
When you send a message over a WebSocket, you don't automatically know which incoming message is its specific reply. It's like sending a letter and waiting for a specific reply letter in a pile of mail!
Unique Request Identifiers
To solve this, we introduce a crucial concept: Message IDs. Every time a client sends a request, it attaches a unique identifier.
The server then processes the request and includes that same identifier in its response. This allows the client to match the response to its original request.
Client-Side Request Tracking
On the client, we need a way to track which requests are pending and what to do when their responses arrive. A common pattern is to use a Map or object to store a Promise for each pending request.
Try running this basic setup in your browser's console:
const ws = new WebSocket("ws://localhost:8080");
const pendingRequests = new Map();
ws.onopen = () => console.log("WebSocket Connected!");
ws.onclose = () => console.log("WebSocket Disconnected.");
ws.onerror = (error) => console.error("WebSocket Error:", error);
// This will be updated later to handle responsesServer Responds with ID
The server's role is simple: when it receives a message with an id, it should process it and send back a response that includes the same id.
Here's a simplified Node.js server snippet:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
ws.on('message', message => {
const request = JSON.parse(message);
console.log('Received:', request);
// Assume processing takes time...
setTimeout(() => {
const response = {
id: request.id, // Echo the original ID!
type: 'response',
payload: `Hello from server, for request ${request.id}`
};
ws.send(JSON.stringify(response));
}, 1000);
});
});
console.log('Server started on ws://localhost:8080');The Full Cycle in Action
Let's trace a request-response cycle:
- Client generates unique
id(e.g., 1). - Client stores a
Promiseforid: 1inpendingRequests. - Client sends
{id: 1, type: 'fetchUser', userId: 123}. - Server receives, processes, and prepares response.
- Server sends
{id: 1, type: 'userFetched', data: {...}}. - Client receives message, looks up
id: 1inpendingRequests, and resolves itsPromise.
A `sendRequest` Function
To make sending requests easier, we can wrap the logic in a helper function. This function will generate an ID, store a promise, send the message, and return the promise.
Add this to your client-side code:
let nextRequestId = 0;
function sendRequest(type, payload) {
const requestId = nextRequestId++;
const message = { id: requestId, type, payload };
return new Promise((resolve, reject) => {
pendingRequests.set(requestId, { resolve, reject, timeoutId: null });
ws.send(JSON.stringify(message));
console.log("Sent request:", message);
// We'll add timeout logic soon!
});
}
// Example usage (after ws is open):
// sendRequest('getUser', { id: 1 }).then(data => console.log(data));Processing Server Responses
Now, let's update our client's ws.onmessage handler to correctly process incoming server responses and resolve (or reject) the associated promises.
This is where the pendingRequests map truly shines!
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log("Received:", message);
const { id, error, payload } = message;
if (pendingRequests.has(id)) {
const { resolve, reject, timeoutId } = pendingRequests.get(id);
clearTimeout(timeoutId); // Important: clear the timeout!
pendingRequests.delete(id); // Remove from tracking
if (error) {
reject(new Error(error));
} else {
resolve(payload); // Resolve with the response payload
}
} else {
console.warn("Unmatched message ID or broadcast received:", message);
// Handle messages that are not direct responses to a request (e.g., broadcasts)
}
};Timeouts and Error Handling
What if the server never responds? Or the connection drops?
It's crucial to implement timeouts for pending requests. If a response isn't received within a set duration, the client should automatically reject the promise with a timeout error.
This prevents requests from hanging indefinitely and consuming memory.
Check Your Understanding
Which of the following are essential components for implementing a robust request-response pattern over WebSockets?
Recap: Request-Response
You've learned how to simulate a traditional request-response model using WebSockets!
- Unique Message IDs: Attach an ID to each request.
- Client-Side Tracking: Use a
Mapto storePromises for pending requests. - Server Echo: Server includes the request ID in its response.
- Timeouts: Implement timeouts to handle unreceived responses gracefully.
This pattern makes WebSockets incredibly versatile for both streaming and discrete data exchanges!
常见问题解答
「通过 WebSockets 实现请求-响应」课时是免费的吗?
是的 — 「通过 WebSockets 实现请求-响应」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Realtime Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。
「通过 WebSockets 实现请求-响应」这节课中我会学到什么?
学习使用 WebSocket 消息 ID 和确认机制,模拟传统请求-响应语义的技术。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Realtime Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 WebSockets & Realtime Systems Programming 需要有经验吗?
无需任何先前经验。CoddyKit 上的 WebSockets & Realtime Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「通过 WebSockets 实现请求-响应」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 WebSockets & Realtime Systems Programming 课中编写并运行代码吗?
能。每节 WebSockets & Realtime Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 实现发布/订阅消息
- 通过 WebSockets 实现请求-响应
- 双向流式传输与流量控制
- 背压与消息批处理