0Pricing
Real-Time Streaming Systems (WebRTC + Live Data) · 강의

데이터 송수신

설정된 WebRTC 데이터 채널을 통해 다양한 유형의 데이터(텍스트, 이진 데이터)를 송수신하는 코드 예제를 구현합니다.

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

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

Messaging with Data Channels

WebRTC's RTCDataChannel isn't just for connection; it's also for sending messages! This lets peers exchange arbitrary data directly.

Think of it like a super-fast, secure chat line between two browsers, but for any kind of information you want to share.

Sending Data with `send()`

To send data, you use the send() method of an RTCDataChannel object. It's straightforward and can handle various data types.

  • Syntax: dataChannel.send(data);
  • The data can be a String, Blob, ArrayBuffer, or ArrayBufferView.

The channel must be in an 'open' state to send messages.

Text Messages are Easy

The simplest data to send is plain text. This is perfect for chat messages, commands, or small bits of structured data like JSON strings.

When you pass a JavaScript String to send(), it's sent as text data.

// Assuming 'dataChannel' is an open RTCDataChannel
dataChannel.send("Hello from CoddyKit!");
dataChannel.send(JSON.stringify({ type: "chat", message: "Hi!" }));

Try Sending a Text Message

Let's simulate sending a simple text message. In a real scenario, this would go to a connected peer. Here, we log what we're "sending."

const dataChannel = {
  readyState: "open",
  send: function(data) {
    if (this.readyState === "open") {
      console.log("DataChannel sending:", data);
    } else {
      console.error("DataChannel not open.");
    }
  }
};

if (dataChannel.readyState === "open") {
  dataChannel.send("Welcome to real-time data!");
  dataChannel.send("Your first message sent!");
} else {
  console.log("Data channel is not yet open.");
}

Handling Incoming Messages

To receive data, you listen for the message event on your RTCDataChannel object. This event fires whenever a peer sends data.

  • The event handler is typically set via dataChannel.onmessage.
  • The event object (MessageEvent) has a data property, which contains the received message.

The type of event.data depends on what was sent (String or Blob/ArrayBuffer).

Sending and Receiving Text

Here's a combined example. One "peer" sends a message, and another "peer" (simulated here) receives it using onmessage.

const senderChannel = {
  readyState: "open",
  send: function(data) {
    if (this.readyState === "open") {
      console.log("Sender sent:", data);
      receiverChannel.onmessage({ data: data });
    }
  }
};

const receiverChannel = {
  readyState: "open",
  onmessage: function(event) {
    console.log("Receiver received:", event.data);
  }
};

senderChannel.send("Hello from sender!");

Beyond Text: Binary Data

While strings are great for text, RTCDataChannel also supports sending binary data efficiently. This is crucial for things like file sharing, game state updates, or image data.

You can send:

  • Blob: Represents raw immutable data. Good for files.
  • ArrayBuffer: A fixed-length raw binary data buffer.
  • ArrayBufferView: A view into an ArrayBuffer (e.g., Uint8Array).

When binary data is received, event.data will be an ArrayBuffer or Blob, depending on the channel's binaryType property.

Using ArrayBuffer for Binary

ArrayBuffer is a common way to handle raw binary data in JavaScript. You can create views (like Uint8Array) to manipulate its contents.

// Create an ArrayBuffer
const buffer = new ArrayBuffer(4); // 4 bytes
const view = new Uint8Array(buffer);

// Put some data into the view
view[0] = 65; // ASCII 'A'
view[1] = 66; // ASCII 'B'
view[2] = 67; // ASCII 'C'
view[3] = 68; // ASCII 'D'

// Send the ArrayBuffer
dataChannel.send(buffer);

The receiver will get this ArrayBuffer and can then interpret it.

Binary Data in Action

Let's simulate sending an ArrayBuffer and then interpreting it on the receiving end. We'll convert the received bytes back to characters for display.

const senderBinaryChannel = {
  readyState: "open",
  send: function(data) {
    if (this.readyState === "open") {
      console.log("Sender sent binary data.");
      receiverBinaryChannel.onmessage({ data: data });
    }
  }
};

const receiverBinaryChannel = {
  readyState: "open",
  onmessage: function(event) {
    console.log("Receiver received binary data.");
    const receivedBuffer = event.data;
    if (receivedBuffer instanceof ArrayBuffer) {
      const view = new Uint8Array(receivedBuffer);
      let receivedChars = "";
      for (let i = 0; i < view.length; i++) {
        receivedChars += String.fromCharCode(view[i]);
      }
      console.log("Decoded binary:", receivedChars);
    }
  }
};

const buffer = new ArrayBuffer(3);
const view = new Uint8Array(buffer);
view[0] = 72; // H
view[1] = 73; // I
view[2] = 33; // !

senderBinaryChannel.send(buffer);

Data Channel Check

You've learned how to send and receive different types of data. Let's test your understanding!

Sending & Receiving Data Recap

Great job! You've mastered the basics of sending and receiving data over WebRTC Data Channels.

  • We use dataChannel.send(data) to transmit information.
  • The onmessage event listener handles incoming data from peers.
  • Data Channels support both text (String) and various binary types (Blob, ArrayBuffer).

This capability opens up a world of possibilities for real-time collaboration and direct data exchange!

자주 묻는 질문

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

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

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

설정된 WebRTC 데이터 채널을 통해 다양한 유형의 데이터(텍스트, 이진 데이터)를 송수신하는 코드 예제를 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Real-Time Streaming Systems (WebRTC + Live Data)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Real-Time Streaming Systems (WebRTC + Live Data)을(를) 시작하는 데 경험이 필요한가요?

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

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

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

이 Real-Time Streaming Systems (WebRTC + Live Data) 강의에서 코드를 작성하고 실행할 수 있나요?

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

이 강의의 모든 강의

  1. RTCDataChannel 소개
  2. 데이터 송수신
  3. 데이터 채널의 실전 활용 사례
  4. 신뢰성 있는 데이터 채널과 신뢰성 없는 데이터 채널
← Real-Time Streaming Systems (WebRTC + Live Data)(으)로 돌아가기