Standard WebRTC obejmuje również interfejs API do wysyłania dowolnych danych przez RTCPeerConnection
. Odbywa się to poprzez wywołanie funkcji createDataChannel()
na obiekcie RTCPeerConnection
, który zwraca obiekt RTCDataChannel
.
const peerConnection = new RTCPeerConnection(configuration);
const dataChannel = peerConnection.createDataChannel();
Zdalny datachannel
może odbierać kanały danych, nasłuchując zdarzenia RTCPeerConnection
obiekcie RTCPeerConnection
. Odebrane zdarzenie jest typu RTCDataChannelEvent
i zawiera właściwość channel
która reprezentuje RTCDataChannel
połączone między RTCDataChannel
.
const peerConnection = new RTCPeerConnection(configuration);
peerConnection.addEventListener('datachannel', event => {
const dataChannel = event.channel;
});
Otwórz i zamknij wydarzenia
Zanim kanał danych będzie mógł zostać użyty do wysyłania danych, klient musi poczekać, aż zostanie otwarty. Odbywa się to poprzez słuchanie open
wydarzenia. Podobnie ma miejsce zdarzenie close
, gdy którakolwiek ze stron zamyka 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
Wysłanie wiadomości na RTCDataChannel
odbywa się poprzez wywołanie funkcji send()
z danymi, które chcemy wysłać. Parametr data
dla tej funkcji może być ciągiem, obiektem Blob
, ArrayBuffer
lub i 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 RTCDataChannel
otrzyma komunikaty wysłane w RTCDataChannel
, nasłuchując 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';
});