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

Daten senden und empfangen

Implementieren Sie Codebeispiele zum Senden und Empfangen verschiedener Datentypen (Text, Binärdaten) über einen eingerichteten WebRTC-Datenkanal.

Daten senden und empfangen ist eine kostenlose Real-Time Streaming Systems (WebRTC + Live Data)-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Real-Time Streaming Systems (WebRTC + Live Data)-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Real-Time Streaming Systems (WebRTC + Live Data)-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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!

Häufig gestellte Fragen

Ist die Lektion „Daten senden und empfangen“ kostenlos?

Ja — der vollständige Text von „Daten senden und empfangen“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Real-Time Streaming Systems (WebRTC + Live Data)-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Real-Time Streaming Systems (WebRTC + Live Data)-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Daten senden und empfangen“?

Implementieren Sie Codebeispiele zum Senden und Empfangen verschiedener Datentypen (Text, Binärdaten) über einen eingerichteten WebRTC-Datenkanal. Du übst Real-Time Streaming Systems (WebRTC + Live Data) mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Real-Time Streaming Systems (WebRTC + Live Data) zu starten?

Keine Vorkenntnisse erforderlich. Real-Time Streaming Systems (WebRTC + Live Data) auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.

Wie lange dauert die Lektion „Daten senden und empfangen“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Real-Time Streaming Systems (WebRTC + Live Data)-Lektion Code schreiben und ausführen?

Ja. Jede Real-Time Streaming Systems (WebRTC + Live Data)-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Einführung in RTCDataChannel
  2. Daten senden und empfangen
  3. Praktische Anwendungsfälle für Datenkanäle
  4. Zuverlässige und unzuverlässige Data Channels
← Zurück zu Real-Time Streaming Systems (WebRTC + Live Data)