0Pricing
WebSockets & Realtime Systems Programming · บทเรียน

คำขอและการตอบกลับผ่าน WebSockets

เรียนรู้เทคนิคจำลองความหมายของคำขอและการตอบกลับแบบดั้งเดิมด้วยรหัสข้อความและการยืนยันการรับของ WebSocket

คำขอและการตอบกลับผ่าน WebSockets เป็นบทเรียน WebSockets & Realtime Systems Programming ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 responses

Server 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 Promise for id: 1 in pendingRequests.
  • 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: 1 in pendingRequests, and resolves its Promise.

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 Map to store Promises 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 ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Realtime Systems Programming ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “คำขอและการตอบกลับผ่าน WebSockets”

เรียนรู้เทคนิคจำลองความหมายของคำขอและการตอบกลับแบบดั้งเดิมด้วยรหัสข้อความและการยืนยันการรับของ WebSocket คุณปฏิบัติ WebSockets & Realtime Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Realtime Systems Programming หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Realtime Systems Programming บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “คำขอและการตอบกลับผ่าน WebSockets” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Realtime Systems Programming นี้ได้ไหม

ได้ บทเรียน WebSockets & Realtime Systems Programming ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การใช้งานการส่งข้อความแบบเผยแพร่และสมัครรับ
  2. คำขอและการตอบกลับผ่าน WebSockets
  3. การสตรีมแบบสองทิศทางและการควบคุมการไหล
  4. แรงดันย้อนกลับและการรวมกลุ่มข้อความ
← กลับไปที่ WebSockets & Realtime Systems Programming