summaryrefslogtreecommitdiff
path: root/example/index.js
blob: 35fdbba6e9a6514bcd7ac472b48d2f86790c7a3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
window.onload = function demo() {
  // create peer connection
  let pc = new RTCPeerConnection({
    iceCandidatePoolSize: 4
  });

  // create websocket for signaling channel
  let ws = new WebSocket('ws://localhost:8080');

  // (callback) called upon discovery of new local ICE candidate
  pc.onicecandidate = function(event) {
    if (event.candidate) {
      console.log("local candidate:\n%c%s", "color: green", event.candidate.candidate);
      ws.send(JSON.stringify(event.candidate));
    }
  };

  // (callback) called upon reception of new remote video track
  pc.ontrack = function(event) {
    document.getElementById("remoteVideo").srcObject = event.streams[0];
  };

  // receive remote answer or candidate
  ws.onmessage = function(event) {
    try {
      let d = JSON.parse(event.data);
      if ('candidate' in d) {
        if (d.candidate) {
          console.log("remote candidate:\n%c%s", "color: blue;", event.data);
        }
      } else if ('sdp' in d) {
        console.log("remote answer:\n%c%s", "color: blue;", event.data);
      }
    } catch(e) {
      console.log("remote error:\n%c%s", "color: red;", event.data);
    }
  };

  // create offer and set to remote peer
  ws.onopen = function(event) {
    pc.createOffer({ offerToReceiveVideo: true }).then(function(offer) {
      console.log("local offer:\n%c%s", "color: green;", offer.sdp);
      pc.setLocalDescription(offer);
      ws.send(JSON.stringify(offer));
    });
  };
}