WebRTC 标准还涵盖用于通过 RTCPeerConnection
发送任意数据的 API。可通过对 RTCPeerConnection
对象调用 createDataChannel()
来完成此操作,该方法会返回 RTCDataChannel
对象。
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';
});