我是webrtc的新手,我不太清楚我是否可以使用RTCPeerConnection对象(我用它来正确传输媒体)来创建数据通道,或者我必须为数据传输做单独的信令。
由于
答案 0 :(得分:2)
是(在Chrome中使用https fiddle):
var pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
var add = (pc, can) => can && pc.addIceCandidate(can).catch(log);
pc1.onicecandidate = e => add(pc2, e.candidate);
pc2.onicecandidate = e => add(pc1, e.candidate);
pc1.oniceconnectionstatechange = e => log(pc1.iceConnectionState);
var dc1, dc2;
pc2.ondatachannel = e => {
dc2 = e.channel;
dc2.onopen = () => log("Chat!");
dc2.onmessage = e => log("> " + e.data);
};
var start = () => navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
pc1.addStream(video1.srcObject = stream);
dc1 = pc1.createDataChannel("chat");
dc1.onopen = () => (chat.disabled = false, chat.select());
return pc1.createOffer();
})
.then(offer => pc1.setLocalDescription(offer))
.then(() => pc2.setRemoteDescription(pc1.localDescription))
.then(() => pc2.createAnswer())
.then(answer => pc2.setLocalDescription(answer))
.then(() => pc1.setRemoteDescription(pc2.localDescription))
.catch(log);
chat.onkeypress = e => {
if (e.keyCode != 13) return;
dc1.send(chat.value);
chat.value = "";
};
var log = msg => div.innerHTML += "<br>" + msg;
<video id="video1" height="120" width="160" autoplay muted></video>
<video id="video2" height="120" width="160" autoplay></video><br>
<button onclick="start()">Start!</button>
Chat: <input id="chat" disabled></input><br><div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>