garageScript / curriculum

GarageScript Curriculum
21 stars 164 forks source link

[Tutorial] - Webrtc peer connection #357

Open songz opened 3 years ago

songz commented 3 years ago

WEBRTC

Prerequisites

Fundamentally, the way the web works currently like this:

Request / Response Image

All request / response to the World Wide Web is actually based on the ip address of your router / modem. This is not gonna work for P2P. For P2P, you need to establish a direct connection from computer to computer. We use a STUN server to help establish a connection between 2 computers directly. Unfortunately, STUN server can't help you establish direct connections when a computer is within an complex internal network with VPNs and Proxies (usually within corporate companies). When this happens, you can use a TURN server. Since direct P2P cannot be established, TURN server handles media and data like a middleman between 2 computers.

Since TURN server may have to handle alot of media data, companies usually don't let you use their TURN server for free. Good news is, you can set one up yourself for free

We will be building a group video chat app.

Overview:

  1. When the page loads, we try to get the user's webcam. After getting it, we run the sendBroadcast function that broadcasts an event to tell everyone in the channel that I have a video! Eventname: broadcastAvailable.
  2. When the page receives a broadcastAvailable event, the page checks to see if the
  3. Watchers (/watch) are gonna receive the event. If they are already watching that stream, then they're like... I can ignore this. Otherwise, they'll send a message to the broadcaster saying... I want this. Let's call that event getBroadcast.
  4. When Broadcaster receives the getBroadcast event, it creates a peer connection object with a stun server (provided by google woohoo!). Then when it receives an ICE Candidate (aka information about its client data), it needs to send that to the watcher: iceOfferCandidate.
  5. Watcher receives iceOfferCandidate event, creates a peerConnection and adds the offerCandidate