Standard WebRTC obejmuje również interfejs API do wysyłania dowolnych danych przez
RTCPeerConnection Aby to zrobić, wywołaj createDataChannel() na
Obiekt RTCPeerConnection, który zwraca obiekt RTCDataChannel.
const peerConnection = new RTCPeerConnection(configuration);
const dataChannel = peerConnection.createDataChannel();
Zdalny peer może odbierać kanały danych przez nasłuchiwanie datachannel
w obiekcie RTCPeerConnection. Odebrane zdarzenie jest typu
RTCDataChannelEvent i zawiera właściwość channel, która reprezentuje
Połączenia równorzędne: RTCDataChannel.
const peerConnection = new RTCPeerConnection(configuration);
peerConnection.addEventListener('datachannel', event => {
const dataChannel = event.channel;
});
Otwieranie i zamykanie wydarzeń
Zanim będzie można użyć kanału danych do wysyłania danych, klient musi poczekać
do chwili otwarcia. W tym celu nasłuchuje zdarzenia open.
Podobnie istnieje zdarzenie close, które wiąże się z zamknięciem kanału przez dowolną ze stron.
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
Wysyłanie wiadomości za pomocą urządzenia RTCDataChannel można wysłać przez wywołanie funkcji send()
z danymi, które chcemy wysyłać. Parametr data dla tej funkcji może być
może to być ciąg, 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 peer będzie otrzymywać wiadomości wysłane za pomocą urządzenia RTCDataChannel przez nasłuchiwanie
zdarzenie 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';
});