Google is committed to advancing racial equity for Black communities. See how.
本頁面由 Cloud Translation API 翻譯而成。
Switch to English

數據通道

WebRTC標準還涵蓋了用於通過RTCPeerConnection發送任意數據的API。這是通過在RTCPeerConnectionRTCPeerConnection上調用createDataChannel()來完成的,該對象將返回RTCDataChannel對象。

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

遠程對等方可以通過偵聽RTCPeerConnectionRTCPeerConnection上的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;
});
 

留言內容

通過使用我們要發送的數據調用send()函數,可以在RTCDataChannel上發送消息。該函數的data參數可以是字符串, BlobArrayBuffer或and 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事件來接收在RTCDataChannelmessage

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