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.
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.
const peerConnection = new RTCPeerConnection(configuration);
peerConnection.addEventListener('datachannel', event => {
const dataChannel = event.channel;
});
打开和关闭事件
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;
});
消息
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
.
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.
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';
});