Skip to content

Instantly share code, notes, and snippets.

@qutek
Created April 20, 2022 19:21
Show Gist options
  • Save qutek/f6029d160171c177b6a79010682ab504 to your computer and use it in GitHub Desktop.
Save qutek/f6029d160171c177b6a79010682ab504 to your computer and use it in GitHub Desktop.
[WebRTC] Play with WebRTC

Playing arround with WebRTC

Open 2 browsers and paste this code to the console

A - Create RTC connection

const peerConnection = new RTCPeerConnection();

peerConnection.onicecandidate = (e) => {
  console.log("Peer A onicecandidate", peerConnection.localDescription);
};

const channel = peerConnection.createDataChannel("channel-name");
channel.onmessage = (e) => console.log("Peer A - Got message", e.data);
channel.onopen = (e) => console.log("Peer A - Channel opened!");
channel.onclose = (e) => console.log("Peer A - Channel closed!");

B - Create RTC connection

const peerConnection = new RTCPeerConnection();

peerConnection.onicecandidate = (e) => {
  console.log("Peer B onicecandidate", peerConnection.localDescription);
};

let channel;
peerConnection.ondatachannel = ({channel: remoteChannel}) => {
    remoteChannel.onmessage = (e) => console.log("Peer B - Got message", e.data);
    remoteChannel.onopen = (e) => console.log("Peer B - Channel opened!");
    remoteChannel.onclose = (e) => console.log("Peer B - Channel closed!");
    
    channel = remoteChannel;
};

A - Create offer

peerConnection
  .createOffer()
  .then((o) => peerConnection.setLocalDescription(o));

B - Set remote description from offer and create answer

const offer = // copy from A
peerConnection.setRemoteDescription(offer).then((a) => console.log("Peer B - Done setRemoteDescription"));

peerConnection
  .createAnswer()
  .then((a) => peerConnection.setLocalDescription(a))
  .then((a) => console.log(JSON.stringify(peerConnection.localDescription)));

A - Set remote description from answer

const answer = // copy from B
peerConnection.setRemoteDescription(answer).then(a=>console.log("Peer A - Done setRemoteDescription"))

A or B

channel.send('text')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment