Kanały danych

Standard WebRTC obejmuje też interfejs API do wysyłania dowolnych danych przez interfejs RTCPeerConnection. W tym celu wywołaj createDataChannel() obiektem RTCPeerConnection, który zwraca obiekt RTCDataChannel.

const peerConnection = new RTCPeerConnection(configuration);
const dataChannel = peerConnection.createDataChannel();

Zdalny partner może otrzymywać kanały danych, nasłuchując zdarzenia datachannel w obiekcie RTCPeerConnection. Odebrane zdarzenie jest typu RTCDataChannelEvent i zawiera właściwość channel, która reprezentuje RTCDataChannel połączony z połączeniami równorzędnymi.

const peerConnection = new RTCPeerConnection(configuration);
peerConnection.addEventListener('datachannel', event => {
    const dataChannel = event.channel;
});

Otwieranie i zamykanie wydarzeń

Aby można było użyć kanału danych do wysyłania danych, klient musi poczekać do otwarcia kanału. Odbywa się to poprzez nasłuchiwanie zdarzenia open. Jest też zdarzenie close, które następuje, gdy któraś ze stron zamknie kanał.

const messageBox = document.querySelector('#messageBox');
const sendButton = document.querySelector('#sendButton');
const peerConnection = new RTCPeerConnection(configuration);
const dataChannel = peerConnection.createDataChannel();

// Enable textarea and button when opened
dataChannel.addEventListener('open', event => {
    messageBox.disabled = false;
    messageBox.focus();
    sendButton.disabled = false;
});

// Disable input when closed
dataChannel.addEventListener('close', event => {
    messageBox.disabled = false;
    sendButton.disabled = false;
});

Wiadomości

Aby wysłać wiadomość na urządzeniu RTCDataChannel, wywołaj funkcję send() z danymi, które chcesz wysłać. Parametr data dla tej funkcji może być ciągiem znaków, Blob, ArrayBuffer lub ArrayBufferView.

const messageBox = document.querySelector('#messageBox');
const sendButton = document.querySelector('#sendButton');

// Send a simple text message when we click the button
sendButton.addEventListener('click', event => {
    const message = messageBox.textContent;
    dataChannel.send(message);
})

Zdalny partner będzie otrzymywać wiadomości wysyłane na urządzenie RTCDataChannel przez nasłuchiwanie zdarzenia message.

const incomingMessages = document.querySelector('#incomingMessages');

const peerConnection = new RTCPeerConnection(configuration);
const dataChannel = peerConnection.createDataChannel();

// Append new messages to the box of incoming messages
dataChannel.addEventListener('message', event => {
    const message = event.data;
    incomingMessages.textContent += message + '\n';
});