WebRTC and PeerJS Video Chatting

Niraj
4 min readNov 19, 2021

Build your own peer-to-peer video chat app with a WebRTC framework called PeerJS

PeerJS using WebRTC

Introduction

Webrtc lets you exchange real-time audio and video streams with your friends entirely in the browser. If you want to build your own video chatting app WebRTC is the api you’re looking for because it allows you to establish a peer-to-peer connection between two or more browsers. These browsers can exchange audio and video media directly without the need for a third-party server or native app.

  • The first pier will create an offer asking for another peer to connect to them this will result in an SDP object or session description protocol which contains information describing the peer-to-peer connection like the video codec timing.
  • The data will be saved in a server where it can then be read by another peer to answer the call which is achieved by creating an SDP answer and writing that to the server this process is known as signaling and it’s handled by a third party server the signaling server allows the two parties to securely exchange connection data.
  • Interactive connectivity establishment allows both peers to generate a list of ice candidates which contain an ip address and port that a peer can use to connect to another peer. Then each peer will save their ice candidates in the database where they can then be read by the other peer. ICE will pick the best candidate an begin to flow the video and audio between the two peers

The PeerJS library, builds on top of WebRTC. PeerJS wraps the browser’s WebRTC and provides a peer-to-peer connection API. Also provides it’s own global servers

Setup PeerJs

Include the library

<script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js"></script>ornpx peerjs --port 9000

Create the Peer

var peer = new Peer(); //The Peer object is where we create and receive connections.

PeerJS uses PeerServer for session metadata and candidate signaling

Peer Id’s

Every Peer object is assigned a random, unique ID when it’s created.

peer.on('open', function(id) {
console.log('My peer ID is: ' + id);
});

When we want to connect to another peer, we’ll need to know their peer id.

PeerJs data connections

To start a data connection you need to call peer.connect with the peer ID of the destination peer. When the other person try’s to connect to your peer ID, there will be a connection event that has happened.

Connect

peer.connect along with the callback of the connection event will create a object for you and this object lets the user send and receive messages back and forth. For further explanation refer to the code below:

var conn = peer.connect('another-peers-id');// on open will be launch when you successfully connect to PeerServerconn.on('open', function() {
// Receive messages
conn.on('data', function(data) {
console.log('Received', data);
});

// Send messages
conn.send('Hello!');
});

Receive

peer.on('connection', function(conn) {
conn.on('data', function(data){
// Will print 'hello!'
console.log(data);
});
});

Video & Audio calls

You can call another person by using peer.call with the peer ID of the other person. And when someone calls you the call event will be send forth.

Just like phones you need to accept the call for there to be a connection, in our case the data connection will happen when the call is answered.

Call

var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
getUserMedia({video: true, audio: true}, function(stream) {
var call = peer.call('another-peers-id', stream);
call.on('stream', function(remoteStream) {
// Show stream in some video/canvas element.
});
}, function(err) {
console.log('Failed to get local stream' ,err);
});

Answer

var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
peer.on('call', function(call) {
getUserMedia({video: true, audio: true}, function(stream) {
call.answer(stream); // Answer the call with an A/V stream.
call.on('stream', function(remoteStream) {
// Show stream in some video/canvas element.
});
}, function(err) {
console.log('Failed to get local stream' ,err);
});
});

TURN servers

You can create a ICE servers as the config key of the options hash. Since the actual data doesn’t touch the server the connection speed is limited only by the upload and download rates of the two peers.

var peer = new Peer({
config: {'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
{ url: 'turn:homeo@turn.bistri.com:80', credential: 'homeo' }
]} /* Sample servers, please use appropriate ones */
});

Have fun trying to create your own video chatting application. 😊

--

--