WebRTC 표준은 RTCPeerConnection
를 통해 임의의 데이터를 전송하기 위한 API도 다룹니다. 이렇게 하려면 RTCDataChannel
객체를 반환하는 RTCPeerConnection
객체의 createDataChannel()
를 호출하면 됩니다.
const peerConnection = new RTCPeerConnection(configuration);
const dataChannel = peerConnection.createDataChannel();
원격 피어는 RTCPeerConnection
객체의 datachannel
이벤트를 수신하여 데이터 채널을 수신할 수 있습니다. 수신된 이벤트는 RTCDataChannelEvent
유형이며 동종 앱 간에 연결된 RTCDataChannel
를 나타내는 channel
속성을 포함합니다.
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';
});