This article was peer reviewed by Panayiotis Velisarakos and Ravi Kiran. Thanks to all of SitePoint's peer reviewers for making SitePoint content the best it can be!
With the advent of WebRTC and the increasing capacity of browsers to handle peer-to-peer communications in real-time, it's easier than ever to build real-time applications. In this tutorial we'll take a look at PeerJS and how it can make our lives easier when implementing WebRTC. Throughout this tutorial we'll be building a WebRTC video chat app with messaging features. If you need a bit of a background regarding WebRTC and peer-to-peer communication, I recommend reading The Dawn of WebRTC and Introduction to the getUserMedia API.
What Is PeerJS?
[author_more]
Before we move on, it's important that we understand the main tool that we'll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, video, and audio calls.
What it does is act as a wrapper around the browser's WebRTC implementation. As you might already know, browser vendors doesn't exactly agree on a single way of implementing different features which means that for every browser there's a different implementation for WebRTC. You as the developer would have to write different code for every browser that you plan to support. PeerJS acts as the wrapper for that code. The API that it exposes is easy to use and understand which makes it a really great candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn't completely peer-to-peer. The reality is that there's always a server which bridges the connection between peers. Two or more devices can't just magically create a connection out of thin air. There are firewalls, routers and other roadblocks that can get in the way of peer-to-peer communication, which is where a server comes in.
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 it your own by using the PeerJS server library or use the PeerServer Cloud Service.
So which is the right choice for your project?
If you want to get started quickly then PeerServer Cloud Service is for you. Just sign up to acquire an API key, which you can then use to connect to the PeerServer Cloud. The only downside to this option is that it doesn't really work in production. This is because you can only have 50 concurrent connections and the server isn't in HTTPS. The video call feature requires end-to-end encryption, which means that the PeerServer that you are connecting to should be in HTTPS as well.
If you're reading this tutorial to implement video or audio call features on your website then you will need the PeerJS server library. However, if you simply need a chat feature you can still use the PeerServer Cloud Service, provided your website doesn't exceed the concurrent connection limit.
As we move on through this tutorial I'll be showing you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Video Chat App
Now it's time to get our hands dirty by building the app. First we're going to work with the client-side code and then we'll move over to the server side.
Please note that you can download the code for this tutorial from our GitHub repo. To run it, or to follow along at home, you will need to have Node and npm installed. If you're not familiar with these, or would like some help getting them installed, check out our previous tutorials:
The Client
In this section we'll be working primarily with the user-facing part of the app. This will have the following directory structure:
public
├── css
│ └── style.css
├── index.html
├── js
│ └── script.js
└── package.json
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event handling.
- PeerJS — the client-side component of PeerJS.
- Handlebars — a JavaScript templating library. We're going to use it for generating HTML for the messages.
You can install the libraries through npm. Create a package.json
file in the root of the public
directory and add the following:
{
"name": "peer-messenger-client",
"version": "0.0.1",
"dependencies": {
"jquery": "~2.1.4",
"picnic": "~4.1.2",
"peerjs": "~0.3.14",
"handlebars": "~4.0.5"
}
}
Execute npm install
to install all the dependencies.
Mark-Up
The index.html
file is reasonably self explanatory. You can find it here. I've added a couple of inline comments to highlight the important points.
Take a second to notice the Handlebars template for constructing the list of messages. This loops through all the messages in the messages
array. For each iteration of the loop, we display the name of the sender and the actual message. Later on we'll take a look at how the data is being passed into this template.
<script id="messages-template" type="text/x-handlebars-template">
<li>
<span class="from">:</span>
</li>
</script>
Styling
The app only has minimal styling since most of the prettifying needs are already handled by Picnic. Our additional styles (in css/style.css) include some rules for positioning the elements, hiding things, and overriding the default one's provided by the browser.
Main App Script
The main JavaScript file (in js/script.js) is where all the logic of the app is contained. This includes such things as the login, initiating the call and capturing the users video. Let's take a look at the code.
We start off by declaring a couple of variables—the messages
array, which will be used to store the messages that are sent by each of the peers, peer_id
, which stores the ID of the remote peer, name
, which stores the name of the current user and conn
to store the current peer connection. We also compile the messages
template using Handlebars and store the result in messages_template
:
var messages = [];
var peer_id, name, conn;
var messages_template = Handlebars.compile($('#messages-template').html());
Next, we create a new PeerJS instance which accepts an object containing configuration options. Here, we're specifying the options host
, port
and the path
, as this demo will use the PeerJS server library (I'll go into the configuration for the PeerServer Cloud Service later on). The debug
option allows us to set the verbosity of the debug mode (3
being the highest) and the config
option allows us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a STUN or TURN server. You don't really need to worry about the different terminologies for now. All you need to know is that these servers are used to make sure that the peer connection is successfully established. If you want to dive into to the specifics of WebRTC, I recommend you to read this HTML5Rocks article on WebRTC Basics and/or this Mozilla Hacks article on WebRTC acronyms. If you want to use another STUN or TURN server, you can look at this list of freely available STUN and TURN servers.
Continue reading %Building a WebRTC Video Chat Application with PeerJS%
by Wern Ancheta via SitePoint
No comments:
Post a Comment