In this tutorial, we’ll take a look at PeerJS and how it can make our lives much easier when implementing WebRTC. Throughout this tutorial, we will build a WebRTC video chat application. Remember, practice makes perfect! It’s important to hone your skill set and to be able to add these tech skills to your tech porfolio!
style.css
WebRTC
WebRTC is a technology that enables real-time communication between web browsers. It is relatively new and in fact, it’s not supported by all of the major web browsers yet. However, the increased capacity of browsers and video chat applications are making it easier than ever to build real-time applications these days.Meet PeerJS
PeerJS serves as a wrapper around the browser’s WebRTC implementation. As you might already know, each browser has their own way of implementing different features. This means there is a different implementation of WebRTC for every browser. So as a developer, you would have to write code for every browser that you plan to support. PeerJS acts as a wrapper for that specific code. The API that it provides is easy to use and understand which makes it a great candidate for implementing a cross-browser WebRTC.Building the WebRTC Video Chat App
WebRTC isn’t completely peer-to-peer. There is always a server that can bridge the connection between peers. PeerServer is the server-side component of PeerJS and allows two or more devices to connect together. You have two choices when it comes to PeerServer. You can either implement the video chat application on your own by using the PeerJS server library or use the PeerServer Cloud Service. First, let’s create a video chat application with PeerServer Cloud Service. Go to http://peerjs.com/peerserver and get a key for free.In your app directory, create:
index.htmlPeerJS Video Chat
Please click `allow` on the top of the screen so we can access your webcam and microphone for calls.
It failed to access the webcam and microphone. Make sure to run this demo on an http server and click ‘allow’ when asked for permission by the browser.
Your id: …
Share this id with others so they can call you.
Make a call
Currently in call with …
*, *: before, *: after { -moz - box - sizing: border - box; - webkit - box - sizing: border - box; box - sizing: border - box; }# my - video video { margin - top: 15 px; width: 280 px; height: auto; background - color: #eee; }# peer - video video { width: 100 % ; height: 75 % ; max - height: 480 px; background - color: #eee; }# video - container { padding: 25 px; text - align: center; }# start - error, #config, #receive - call { display: none; }# my - id { font - weight: bold; }script.js
$(function() { // PeerJS object var peer = new Peer({ key: 'YOUR PEERJS API KEY', debug: 3, config: { 'iceServers': [{ url: 'stun:stun1.l.google.com:19302' }, { url: 'turn:numb.viagenie.ca', credential: 'muazkh', username: 'webrtc@live.com' } ] } }); peer.on('open', function() { $('#my-id').text(peer.id); }); navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; peer.on('call', function(call) { // Answer the call automatically (instead of prompting user) for demo purposes call.answer(window.localStream); onReceiveStream(call); }); peer.on('error', function(err) { alert(err.message); // Return to step 2 if error occurs onStart(); }); getVideo(); $('#make-call').click(function() { // Initiate a call! var call = peer.call($('#callto-id').val(), window.localStream); onReceiveStream(call); }); $('#end-call').click(function() { window.existingCall.close(); onStart(); }); function getVideo() { navigator.getUserMedia({ audio: true, video: true }, function(stream) { // Set your video chat application displays var video = $('#my-video' + ' video')[0]; console.log(stream); console.log(video); video.src = window.URL.createObjectURL(stream); window.localStream = stream; onStart(); }, function(error) { $('#start-error').show(); }); } function onStart() { $('#start, #receive-call').hide(); $('#config').show(); } function onReceiveStream(call) { if (window.existingCall) { window.existingCall.close(); } // Wait for stream on the call, then set peer video display call.on('stream', function(stream) { var video1 = $('#peer-video' + ' video')[0]; video1.src = window.URL.createObjectURL(stream); }); window.existingCall = call; $('#peer-id').text(call.peer); call.on('close', onStart); $('#start, #config').hide(); $('#receive-call').show(); } });To run the WebRTC video chat application, you’ll need to have a server that will serve the files we’ve created on the client-side. The getUserMedia API won’t work by simply opening the index.html file on the browser. If you have PHP installed on your machine, you can execute the following command while inside the directory to serve the files.
$ php -S localhost:8080You can then access the app by going to: http://localhost:8080. If you don’t want to use PeerServer Cloud Service, you can create your own PeerServer. For this, we recommend using Node.JS to create PeerServer. Of course, you must have Node.JS installed on your machine first. Node is very easy to install. The installers are available at https://nodejs.org/en/ and vary depending on your OS. In your other apps directory, create a folder named server and add two of the following files to this folder: package.json
{ "name": "peerserver", "version": "0.0.1", "dependencies": { "peer": "^0.2.8" } }peer_server.js
var PeerServer = require('peer').PeerServer; var server = PeerServer({ port: 9000, path: '/peerjs' });After you’ve created two of the files from above, open terminal, in the server directory, install the necessary library by running:
$ npm installThen run the server by in server directory run:
$ node peer_server.jsYou can check your server is running by hitting http://localhost:9000/peerjs. The result should look like this:
{ "name": "PeerJS Server", "description": "A server side element to broker connections between PeerJS clients.", "website": "http://peerjs.com/" }
Now, you can edit the file script.js:
Findvar peer = new Peer({ key: 'YOUR PEERJS API KEY', debug: 3, config: { 'iceServers': [{ url: 'stun:stun1.l.google.com:19302' }, { url: 'turn:numb.viagenie.ca', credential: 'muazkh', username: 'webrtc@live.com' } ] } });And replace by
var peer = new Peer({ host: 'localhost', port: 9000, path: '/peerjs', debug: 3, config: { 'iceServers': [{ url: 'stun:stun1.l.google.com:19302' }, { url: 'turn:numb.viagenie.ca', credential: 'muazkh', username: 'webrtc@live.com' } ] } });Run app by
$php -S localhost:8080And there you have it! Head to Pangara’s blog for more web tutorials and the latest tech trends news.