Data channels
数据信道
The WebRTC standard also covers an API for sending arbitrary data over a RTCPeerConnection
. This is done by calling createDataChannel()
on a RTCPeerConnection
object, which returns a RTCDataChannel
object.
WebRTC标准还涵盖了通过RTCPeerConnection发送任意数据的API。这是通过对RTCPeerConnection对象调用createDataChannel()来完成的,该对象返回一个RTCDataChannel对象。
const peerConnection = new RTCPeerConnection(configuration);
const dataChannel = peerConnection.createDataChannel();
The remote peer can receive data channels by listening for the datachannel
event on the RTCPeerConnection
object. The received event is of the type RTCDataChannelEvent
and contains a channel
property that represents the RTCDataChannel
connected between the peers.
远程对等端可以通过侦听RTCPeerConnection对象上的数据通道事件来接收数据通道。接收到的事件属于RTCDataChannelEvent类型,并且包含一个通道属性,该属性表示对等端之间连接的RTCDataChannel。
const peerConnection = new RTCPeerConnection(configuration);
peerConnection.addEventListener('datachannel', event => {
const dataChannel = event.channel;
});
Open and close events
打开和关闭事件
Before a data channel can be used for sending data, the client needs to wait until it has been opened. This is done by listening to the open
event. Likewise, there is a close
event for when either side closes the channel.
在可以使用数据通道发送数据之前,客户端需要等待它被打开。这是通过侦听打开事件来完成的。同样,当任何一方关闭通道时,也会发生关闭事件。
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;
});
Messages
消息
Sending a message on a RTCDataChannel
is done by calling the send()
function with the data we want to send. The data
parameter for this function can be either a string, a Blob
, an ArrayBuffer
or and ArrayBufferView
.
在RTCDataChannel上发送消息是通过调用带有要发送的数据的send()函数来完成的。此函数的数据参数可以是字符串、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);
})
The remote peer will receive messages sent on a RTCDataChannel
by listening on the message
event.
远程对等端将通过侦听消息事件来接收在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';
});