Canali dati

Lo standard WebRTC copre anche un'API per l'invio di dati arbitrari su una RTCPeerConnection. Ciò viene fatto chiamando createDataChannel() su un oggetto RTCPeerConnection, che restituisce un oggetto RTCDataChannel.

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

Il peer remoto può ricevere canali di dati ascoltando l'evento datachannel sull'oggetto RTCPeerConnection. L'evento ricevuto è del tipo RTCDataChannelEvent e contiene una proprietà channel che rappresenta l'elemento RTCDataChannel connesso tra i peer.

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

Aprire e chiudere gli eventi

Prima di poter utilizzare un canale di dati per l'invio dei dati, il client deve attendere fino all'apertura. Per farlo, devi ascoltare l'evento open. Allo stesso modo, si verifica un evento close per la chiusura di uno dei due lati.

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;
});

Messaggi

L'invio di un messaggio su un RTCDataChannel viene eseguito chiamando la funzione send() con i dati che vogliamo inviare. Il parametro data per questa funzione può essere una stringa, Blob, ArrayBuffer o 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);
})

Il peer remoto riceverà i messaggi inviati su un RTCDataChannel tramite l'ascolto dell'evento 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';
});