Envoyer et recevoir des données
Mettez en œuvre des exemples de code pour envoyer et recevoir différents types de données (texte, données binaires) via un canal de données WebRTC établi.
Envoyer et recevoir des données est une leçon Real-Time Streaming Systems (WebRTC + Live Data) gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Real-Time Streaming Systems (WebRTC + Live Data), et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Real-Time Streaming Systems (WebRTC + Live Data) comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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
datacan be aString,Blob,ArrayBuffer, orArrayBufferView.
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 adataproperty, 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 anArrayBuffer(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
onmessageevent 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!
Apprends Real-Time Streaming Systems (WebRTC + Live Data) avec un tuteur IA — gratuit
Écris et exécute du vrai code dans ton navigateur, obtiens de l'aide instantanée d'un tuteur IA disponible 24h/24, et reprends là où tu t'es arrêté sur le web ou dans l'app.
- Cours
- 12
- Leçons
- 48
Questions Fréquemment Posées
La leçon « Envoyer et recevoir des données » est-elle gratuite ?
Oui — le texte complet de « Envoyer et recevoir des données » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Real-Time Streaming Systems (WebRTC + Live Data), passe à CoddyKit PRO. Le cours Real-Time Streaming Systems (WebRTC + Live Data) comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Envoyer et recevoir des données » ?
Mettez en œuvre des exemples de code pour envoyer et recevoir différents types de données (texte, données binaires) via un canal de données WebRTC établi. Tu pratiques Real-Time Streaming Systems (WebRTC + Live Data) avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Real-Time Streaming Systems (WebRTC + Live Data) ?
Aucune expérience préalable n'est requise. Real-Time Streaming Systems (WebRTC + Live Data) sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.
Combien de temps prend la leçon « Envoyer et recevoir des données » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Real-Time Streaming Systems (WebRTC + Live Data) ?
Oui. Chaque leçon Real-Time Streaming Systems (WebRTC + Live Data) inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Introduction à RTCDataChannel
- Envoyer et recevoir des données
- Cas pratiques d’utilisation des canaux de données
- Canaux de données fiables ou non fiables