データチャネル

WebRTC 標準では、RTCPeerConnection で任意のデータを送信するための API も提供されています。これを行うには、RTCDataChannel オブジェクトを返す RTCPeerConnection オブジェクトに対して createDataChannel() を呼び出します。

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

リモートピアは、RTCPeerConnection オブジェクトで datachannel イベントをリッスンすることでデータチャネルを受信できます。受信したイベントのタイプは RTCDataChannelEvent で、ピア間で接続された RTCDataChannel を表す channel プロパティを含みます。

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

予定を開く、閉じる

データチャネルを使用してデータを送信できるようにするには、クライアントが開くまで待機する必要があります。これを行うには、open イベントをリッスンします。同様に、いずれかの側がチャネルを閉じると、close イベントが発生します。

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

メッセージ

RTCDataChannel でメッセージを送信するには、送信するデータを使用して send() 関数を呼び出します。この関数の data パラメータには、文字列、BlobArrayBufferArrayBufferView を指定できます。

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

リモートピアは、message イベントをリッスンすることで、RTCDataChannel に送信されたメッセージを受信します。

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