WebRTC for Beginners



for Beginners

Copyright © 2013 Muaz Khan<@muazkh>.

If you’re newcomer, newbie or beginner; you’re suggested to tryRTCMultiConnection.js or DataChannel.js libraries.

First of all: you need to get access to microphone and camera if you want to build a video streaming app.

Getting USER MEDIA using Chrome media capture APIs

Getting USER MEDIA using Firefox media capture APIs

There are following possible situations:

  1. A person wants to share camera with his friend(s): so, he will make an offer to his friend to join him.He is the offerer.
  2. A person who receives an offer from a friend: so, he will join him. He is theanswerer.

There are so many other possible situations. Let go to the point.


The first situation: a person wants to make an offer request to his friend. He will create offer sdp and send that sdp to his friend.

First of all: we need to open a peer connection:

webkitRTCPeerConnection (or mozRTCPeerConnection) constructor takes two objects (arguments):

  1. ICE servers (STUN or TURN)
  2. Optional (like RtpDataChannels)

Setting event handlers for peer connection object:

In simple words: onicecandidate returns locally generated ICE candidates so you can pass them over other peer(s) via XHR or Socket.

onaddstream returns remote stream (microphone and camera of your friend!).

peerConnection.addStream attaches your local microphone and camera for other peer.

Creating Offer SDP


Assume that you sent offer sdp to your friend using XHR. Now, “process” that offer sdp and then create answer sdp and send it back to offerer:


And to createAnswer…

Offerer received answer sdp from answerer


Offer/Answer exchange is done. What remaining is ICE candidates.

On getting locally generated ICE

On getting ICE sent by other peer

onaddstream event handling

Wait until remote stream starts flowing

A few tips:

  1. For answerer: NEVER add ICE candidates until that peer generates/creates answer sdp.
  2. Stop adding ICE candidates when remote stream starts flowing.
  3. Don’t create peer connection for answerer until you get offer sdp.

Are you interested in a “more” simple full-fledged guide? Read this document.