Last Updated: February 25, 2016
·
3.84K
· ericraio

WebRTC, Peer-to-Peer Communication with RTCPeerConnection

In my previous article , I discussed about using WebRTC getUserMedia function and how you can request user permission and access the users video and microphone. I recommend reading that article first before reading this one.

So that example worked great for just displaying the content to the browser but it would be more useful to send that data over the network and be able to chat with your friends and we can using RTCPeerConnection.

RTCPeerConnection

This is another API Extension for WebRTC that handles the Peer-to-Peer Connection for getUserMedia. RTCPeerConnection allows two users to communicate directly from browser to browser. We take media streams we get from getUserMedia and plug them into the peer connection and send them off to the other side. When the other side receives them, they will pop out as a new media stream on their peer connection and they can plug them into a video element to display it on the page. So both sides have a peer connection, both get streams from getUserMedia, they plug them in and both streams pop out magically encoded and decoded on the other side. Every RTCPeerConnection has an ICE agent and this is how RTCPeerConnection connects two peers together.

ICE

ICE(Interactive Connectivity Establishment) is used for making the Peer-to-Peer connection for us over the network. ICE first tries to connect peers directly using the lowest possible latency, via UDP. On our network we use a NAT firewall in our browser which prevents us from knowing our public IP address. When behind a firewall, we don’t know what our public ip address is so we send a request to a STUN server to get us our public IP address and then we can create a peer to peer connection. Sometimes STUN doesn’t always work, ICE uses another method called TURN as a fallback. TURN allows us to send the data through a proxy server and it’s guaranteed that our data will get to the other peer but at the cost of latency and bandwidth. Studies show that STUN works most of the time.

HTML5 Rocks has a great article about this and WebRTC, you can read it here. http://www.html5rocks.com/en/tutorials/webrtc/basics/#toc-real