cadid
cadid

Reputation: 21

Is it possible to use the same RTCPeerConnection for both media and data?

I am new to webrtc and I do not have very clear if I can use the RTCPeerConnection object (which I use to transmit media correctly) to create a data channel or instead I have to do a separate signaling for the data transmition.

Thanks

Upvotes: 0

Views: 528

Answers (1)

jib
jib

Reputation: 42430

Yes (use https fiddle in Chrome):

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>

Upvotes: 2

Related Questions