0Pricing
WebSockets & Realtime Systems Programming · 강의

데이터 송수신

서버로 메시지를 보내고 서버에서 들어오는 데이터를 처리하는 메서드를 구현합니다.

데이터 송수신은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Realtime Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Client Data Exchange Intro

Welcome back! In the previous lessons, we learned about establishing WebSocket connections. Now, let's dive into the core of realtime communication: sending and receiving data.

This lesson will show you how to implement methods for clients to send messages to a WebSocket server and how to handle incoming data from that server.

Sending Data with `send()`

To send data from your client to the WebSocket server, you'll use the WebSocket.send() method. It's quite straightforward!

  • You can send various data types: plain text (strings), binary data (like Blob or ArrayBuffer).
  • The server will receive this data and can then process it or even broadcast it to other connected clients.

Basic `send()` Example

Here's a simple JavaScript example demonstrating how to send a text message once the WebSocket connection is open. Remember, ws://localhost:8080 is a common address for a local test server.

const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
  console.log('Connected to server');
  ws.send('Hello from the client!');
};

ws.onerror = (error) => {
  console.error('WS Error:', error);
};

// This example only sends; we'll cover receiving next.

Data Types for `send()`

While sending simple strings is common, WebSockets also support binary data. This is crucial for applications needing to transfer images, audio, or other non-textual information efficiently.

  • String: Most common for text messages, JSON.
  • ArrayBuffer: Raw binary data buffer.
  • Blob: File-like object representing raw data.

The send() method automatically handles the framing for these types.

Receiving Data: `onmessage`

Receiving data from the server is just as important. The WebSocket API provides an event handler called onmessage for this purpose.

When the server sends a message, your client's onmessage function will be triggered. It receives a MessageEvent object, which contains the actual data.

Processing Received Data

Inside the onmessage handler, you access the message content through event.data. The type of event.data depends on what the server sent:

  • If the server sent text, event.data will be a string.
  • If the server sent binary data, event.data will be an ArrayBuffer or a Blob, depending on the WebSocket's binaryType property (default is 'blob').

Basic `onmessage` Example

Let's combine sending and receiving! This client code connects, sends a message, and then listens for any incoming messages, logging them to the console. You'd need a server sending messages back for this to fully demonstrate.

const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
  console.log('Connected to server');
  ws.send('Requesting data...');
};

ws.onmessage = (event) => {
  console.log('Received from server:', event.data);
  // event.data could be string, Blob, or ArrayBuffer
};

ws.onerror = (error) => {
  console.error('WS Error:', error);
};

ws.onclose = () => {
  console.log('Disconnected');
};

Structured Data with JSON

For most modern web applications, sending and receiving structured data is crucial. JSON (JavaScript Object Notation) is the de-facto standard for this.

  • Sending JSON: Use JSON.stringify() to convert your JavaScript object into a JSON string before calling ws.send().
  • Receiving JSON: Use JSON.parse() to convert the incoming JSON string (event.data) back into a JavaScript object.

JSON Communication Example

This example shows how a client can send a structured JSON object to the server and process a JSON response. This pattern is very common for building interactive applications.

const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
  console.log('Connected to server');
  const message = { type: 'greeting', payload: 'Hello Server!' };
  ws.send(JSON.stringify(message));
};

ws.onmessage = (event) => {
  console.log('Raw message:', event.data);
  try {
    const data = JSON.parse(event.data);
    console.log('Parsed JSON:', data);
    if (data.type === 'response') {
      console.log('Server replied:', data.payload);
    }
  } catch (e) {
    console.error('Failed to parse JSON:', e);
  }
};

ws.onerror = (error) => {
  console.error('WS Error:', error);
};

Client Data Handling Quiz

Consider the following client-side WebSocket code snippet:

const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
  ws.send(JSON.stringify({ action: 'subscribe', topic: 'news' }));
};

ws.onmessage = (event) => {
  let msg = event.data;
  if (typeof msg === 'string') {
    msg = JSON.parse(msg);
  }
  console.log(msg.action);
};

If the server sends the string '{"action":"update","data":"new article"}', what will be logged to the console?

Recap: Send & Receive Data

Great job! You've learned the fundamental methods for exchanging data over WebSockets from the client side.

  • Use ws.send() to send text (strings) or binary data (Blob, ArrayBuffer) to the server.
  • Listen for incoming messages using the ws.onmessage event handler.
  • Access the message content via event.data, which can be a string, Blob, or ArrayBuffer.
  • For structured communication, always use JSON.stringify() before sending and JSON.parse() after receiving JSON strings.

Next, we'll explore how to handle other crucial client-side events like connection errors and closures!

자주 묻는 질문

“데이터 송수신” 강의는 무료인가요?

네 — “데이터 송수신” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

“데이터 송수신”에서 뭘 배우나요?

서버로 메시지를 보내고 서버에서 들어오는 데이터를 처리하는 메서드를 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“데이터 송수신” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. 브라우저 WebSocket API 기초
  2. 데이터 송수신
  3. 클라이언트 측 이벤트 처리
  4. 클라이언트 자동 재연결
← WebSockets & Realtime Systems Programming(으)로 돌아가기