介紹 WebRTC APIs 三大核心之一 RTCDataChannel
同樣先實作個簡單應用來當作入門,試試水溫。
RTCDataChannel
主要負責在 peer-to-peer 間建立傳輸資料的通道,比如彼此傳輸文件檔案或照片...等等二進制資源(Binary Object)。
這邊列舉出幾項優點:
利用 RTCDataChannel 實作簡單雙向消息(text messages)傳遞
先附上完整程式碼
這次html模板:
<h1>Use RTCDataChannel to exchange data</h1>
<div id="container">
<textarea id="dataChannelSend" disabled placeholder="Press Start, enter some text, then press Send."></textarea>
<textarea id="dataChannelReceive" disabled></textarea>
<div id="buttons">
<button id="startButton">Start</button>
<button id="sendButton">Send</button>
<button id="closeButton">Stop</button>
</div>
</div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script src="./js/main.js" async></script>
RTCPeerConnection
建立起兩端點的連線溝通,createDataChannel()
建立RTCDataChannel實例。const configuration = null;
localPeer = buildPeerConnection(localPeer, configuration);
datachannel = localPeer.createDataChannel("my local channel"); // 在RTCPeerConnection中建立RTCDataChannel實例
datachannel.onopen = onChannelStageChange(datachannel); // 當channel.[[ReadyState]] 狀態變為 "open"時觸發open事件
datachannel.onclose = onChannelStageChange(datachannel);
remotePeer = buildPeerConnection(remotePeer, configuration);
remotePeer.ondatachannel = receiveChannelCallback; // 綁定datachannel Event
await communication(localPeer, remotePeer); // build peer-to-peer communication
function receiveChannelCallback(event) {
console.log("Receive Channel Callback");
receiveChannel = event.channel; // 接收來自已建立的p2p連線中的Channel
// 將接收到得資料寫進textarea上
receiveChannel.onmessage = event => document.querySelector("textarea#dataChannelReceive").value = event.data;
// 當channel.[[ReadyState]] 狀態變為 "open"時觸發open事件
receiveChannel.onopen = onChannelStageChange(receiveChannel);
receiveChannel.onclose = onChannelStageChange(receiveChannel);
}
receiveChannel
接收來自event(RTCDataChannelEvent
)的channel
屬性,表示與遠端進行datachannel的連結。
因此當localPeer(發送端)透過send()
methods 發送資料時,連結的各個遠端channel就會觸發onmessage
Event,
透過綁定該事件來接收資料。
function send() {
const data = document.querySelector("textarea#dataChannelSend").value;
datachannel.send(data); // localPeer的datachannel觸發send()method 傳遞資料(data)
}
經過上面的實作範例後,會發現跟WebSocket功用很像,但相比之下,RTCDataChannel 有低延遲的特性,更適合應用在即時互動遊戲上,
而在真實使用上,也列出幾個網路上查到得應用範例參考參考:
本章節了解到:
新手入門,如有錯誤,歡迎指正~~~