डेटा चैनल

WebRTC मानक में RTCPeerConnection पर आर्बिट्ररी डेटा भेजने के लिए, एपीआई को भी शामिल किया जाता है. ऐसा करने के लिए 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);
})

रिमोट सहकर्मी को RTCDataChannel इवेंट भेजने पर 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';
});