Establish peer-to-peer WebRTC connections
by fippo
JavaScript
const pc1 = new RTCPeerConnection();
const pc2 = new RTCPeerConnection();
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
async function run() {
const stream = await navigator.mediaDevices.getUserMedia({audio: true, video: true});
stream.getTracks().forEach(t => pc1.addTrack(t, stream));
await pc1.setLocalDescription();
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription();
await pc1.setRemoteDescription(pc2.localDescription);
// Wait 3 seconds.
await (new Promise(r => setTimeout(r, 3000)));
const stats1 = await pc1.getStats();
console.log([...stats1.values()].filter(({type}) => type === 'outbound-rtp').map(r => [r.kind, r.bytesSent]));
pc1.getSenders()[1].replaceTrack(null);
// Wait 3 seconds.
await (new Promise(r => setTimeout(r, 3000)));
const stats2 = await pc1.getStats();
console.log([...stats2.values()].filter(({type}) => type === 'outbound-rtp').map(r => [r.kind, r.bytesSent]))
pc1.getSenders()[1].replaceTrack(stream.getVideoTracks()[0]);
// Just wait 5 seconds.
await (new Promise(r => setTimeout(r, 3000)));
const stats3 = await pc1.getStats();
console.log([...stats3.values()].filter(({type}) => type === 'outbound-rtp').map(r => [r.kind, r.bytesSent]))
}
run();