WebRTC 標準也會涵蓋透過 RTCPeerConnection
傳送任意資料的 API。方法是在傳回 RTCDataChannel
物件的 RTCPeerConnection
物件上呼叫 createDataChannel()
。
const peerConnection = new RTCPeerConnection(configuration);
const dataChannel = peerConnection.createDataChannel();
遠端對等端可監聽 RTCPeerConnection
物件的 datachannel
事件,以接收資料管道。接收到的類型為 RTCDataChannelEvent
,且包含 channel
屬性,代表對等端之間連線的 RTCDataChannel
。
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
參數可以是字串、Blob
、ArrayBuffer
或 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);
})
遠端對等端會監聽 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';
});