นอกจากนี้ มาตรฐาน WebRTC ยังครอบคลุม API สําหรับส่งข้อมูลที่กําหนดเองผ่าน RTCPeerConnection
ซึ่งทําได้โดยการเรียก createDataChannel()
ในออบเจ็กต์ RTCPeerConnection
ซึ่งแสดงผลออบเจ็กต์ RTCDataChannel
const peerConnection = new RTCPeerConnection(configuration);
const dataChannel = peerConnection.createDataChannel();
เพียร์ระยะไกลรับช่องข้อมูลได้ด้วยการฟังเหตุการณ์ datachannel
บนออบเจ็กต์ RTCPeerConnection
เหตุการณ์ที่ได้รับเป็นประเภท 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);
})
เพื่อนอีกคนจะได้รับข้อความที่ส่งใน RTCDataChannel
โดยฟังเหตุการณ์ message
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';
});