0Pricing
WebSockets & Realtime Systems Programming · 강의

WebSockets를 통한 요청-응답

WebSocket 메시지 ID와 확인 응답을 사용하여 기존 요청-응답 의미 체계를 시뮬레이션하는 기법을 배웁니다.

WebSockets를 통한 요청-응답은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 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를 통한 요청-응답” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

“WebSockets를 통한 요청-응답”에서 뭘 배우나요?

WebSocket 메시지 ID와 확인 응답을 사용하여 기존 요청-응답 의미 체계를 시뮬레이션하는 기법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebSockets & Realtime Systems Programming을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Realtime Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“WebSockets를 통한 요청-응답” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebSockets & Realtime Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebSockets & Realtime Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 게시/구독 메시징 구현
  2. WebSockets를 통한 요청-응답
  3. 양방향 스트리밍과 흐름 제어
  4. 역압과 메시지 일괄 처리
← WebSockets & Realtime Systems Programming(으)로 돌아가기