Building a WebRTC Movie Talk Application with PeerJS – SitePoint
Building a WebRTC Movie Talk Application with PeerJS
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 enhancing capacity of browsers to treat peer-to-peer communications in real-time, it’s lighter than ever to build real-time applications. In this tutorial we’ll take a look at PeerJS and how it can make our lives lighter when implementing WebRTC. Via this tutorial we’ll be building a WebRTC movie talk 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?
Before we budge on, it’s significant that we understand the main implement that we’ll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, movie, 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 effortless to use and understand which makes it a indeed superb candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn’t totally peer-to-peer. The reality is that there’s always a server which bridges the connection inbetween peers. Two or more devices can’t just magically create a connection out of lean 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 permits 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 embarked 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 indeed work in production. This is because you can only have fifty concurrent connections and the server isn’t in HTTPS. The movie 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 movie or audio call features on your website then you will need the PeerJS server library. However, if you simply need a talk feature you can still use the PeerServer Cloud Service, provided your website doesn’t exceed the concurrent connection limit.
As we stir on through this tutorial I’ll be showcasing you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Movie Talk App
Now it’s time to get our palms dirty by building the app. Very first we’re going to work with the client-side code and then we’ll budge 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 go after along at home, you will need to have Knot 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:
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event treating.
- 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:
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 duo of inline comments to highlight the significant points.
Take a 2nd 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.
Styling
The app only has minimal styling since most of the prettifying needs are already treated by Picnic. Our extra 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 movie. Let’s take a look at the code.
We embark off by announcing a duo 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 :
Next, we create a fresh PeerJS example 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 permits us to set the verbosity of the debug mode ( three being the highest) and the config option permits us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a Overwhelm or TURN server. You don’t indeed 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 Numb or TURN server, you can look at this list of loosely available Numb and TURN servers.
When the connection has been successfully initialized on the server, the open event is fired on the peer object. At this point the ID of the current user becomes available and we insert it into the page. This user can then give this ID to another user so that they can connect.
The next line adds a getUserMedia property to the navigator object, the value of which will be the flavor of getUserMedia in the browser. For WebKit browsers such as Chrome or Safari, this will be webkitGetUserMedia . For Firefox, this will be mozGetUserMedia . For other browsers which implement the UserMedia API, this will simply be getUserMedia . Note that this isn’t a fool-proof solution. You can use a shim such as getUserMedia.js if you want a more unified way to use the getUserMedia API.
Then comes a function for getting the current user’s movie feed. This uses the navigator.getUserMedia function which accepts three arguments:
- An object containing configuration options. In this case we set the audio and movie to true so both the camera and microphone in the device will work to provide a movie stream.
- A success callback function which we have specified as the argument for the getVideo function. Note that a stream will be passed as an argument into this anonymous callback function.
- An error callback function which simply alerts the user that an error has occurred.
The onReceiveStream function is responsible for initializing the movie stream;
Once the user clicks Log In, we use PeerJS to connect them with the user with the ID they have specified. The metadata object is used to pass in custom-made data to the peer. In this case we’re passing in the username so that we can display it on the peer’s side. Once the connection is established, the data event is triggered every time a message is sent to the current user. For convenience I’m going to refer to the current user (the one who initiates the connection) as User A, and the peer (the one who is being connected to) as User B.
When User A attempts to connect to User B, the connection event is triggered on User B’s peer object. This permits us to set the connection for User B and get the ID of User A ( connection.peer ). From that connection we can listen for the data event which is triggered whenever User A sends a message to User B. After that, we hide the peer ID text field, update its value to use the ID of the connecting peer and demonstrate the username of User A.
The handleMessage function accepts the data that was sent by the remote peer. This data is used to generate the HTML for the list of messages.
As you might imagine, the sendMessage function is used to send messages to a remote peer.
When a user initiates a call, we use the call method provided by the peer object to call the remote peer. The result of this function call comes back an object in which we can listen for the stream event. This event is fired when the movie feed of the remote peer becomes available to the user who initiated the call.
When the current user makes a call to a remote peer, the call event is triggered. From here we execute the onReceiveCall function to accept the call. If you want to add extra functionality for accepting a call, this is a good place to add it.
The onReceiveCall function accepts the current call object as its argument. The the call object’s reaction method is invoked to proceed with the call. This accepts the movie feed of the current user as its argument. When the movie feed of the remote peer becomes available, the stream event is triggered. From there we can call the onReceiveStream function to setup the remote peer’s movie.
The Server
Now we’re ready to proceed with the server. Very first, I’ll look at using the PeerServer Cloud Service, after which I’ll examine how to run your own PeerServer using peerjs-server.
Acquiring an API Key from the PeerServer Cloud Service
Go to peerjs.com and click on the Developer – Free button. This will open a modal window that will ask for your credentials. Pack out the form and click on the Accomplish Registration button. Once that’s done, you’ll be redirected to the dashboard page where you can see your API key.
Copy that and update the js/script.js file with your API key. You can liquidate the host , port and path properties from the configuration options in favour of a key property.
And that’s it. You can now leap to the demo section at the end of the article to see what the finished product looks like. Please bear in mind the limitations of this method (namely that you can only have fifty concurrent connections and that movie is not possible).
Running Your Own PeerServer
In this section I’ll walk you through how to run your own peer server.
This will have the following directory structure:
The server component is going to need the peerjs-server. You can install it by creating a package.json file in the root of the server directory and add the following:
Execute npm install to install the dependencies.
As we’re working locally, the server folder can go alongside your public folder in your project’s root directory (just as we have in our GitHub repo). If you’re not working locally, then the server folder will be on a remote server somewhere.
Creating the PeerServer
Inwards your working directory for the server component, create a peer-server.js file and add the following code:
What this does is create a PeerJS server that runs on port nine thousand . You can run the server by executing knot peer-server.js from the terminal. To check if the server is running, access http://localhost:9000/peerjs from the browser and you should see something similar to the following:
Deploying to a Remote Server
If you’re planning to deploy to a remote server later on, it has to be via HTTPS. This is because browsers only permits access to a device’s camera and microphone if the connection is secure. Here’s the code for the PeerServer to make it run on HTTPS:
This requires you to supply the key and certificate file that you acquired from your SSL certificate provider.
Running the App
To run the WebRTC movie talk app, you’ll need to have a server that will serve the files that we’ve created earlier on the client-side section. This is because the getUserMedia API won’t work by simply opening the index.html file on the browser. There are a entire bunch of ways to do this. Here are some of them:
Using PHP
If you have PHP installed on your machine, you can execute the following instruction while inwards the public directory to serve the files.
You can then access the app by going to: http://localhost:3000.
Using Apache
If you have Apache installed, you can copy the peer-messenger directory over to the root of your web folder and access the app using the following URL: http://localhost/public.
Using Knot
If you want to use Knot, you can install Express and have it serve the static files. You can install Express with the following instruction:
Next, create an app-server.js file and add the following code:
You can then run the app by executing knot app-server.js . And you can access it by going to: http://localhost:3000.
Whichever method you choose, here’s what the app should look like:
From there the user can come in their username and the ID of the peer they’re attempting to connect to. For convenience let’s call this user the “initiator” because he is the one initiating the connection:
Once the initiator has logged in, peerJS sends the connection data to the peer. For convenience let’s call this user the “receiver”. Once the data is received on the receiver’s side, the screen is updated to showcase the username of the initiator.
The receiver can then come in their username and click on the Login button to begin talking to the initiator:
The initiator replies and clicks on the Call button:
Once the call goes through, the initiator and the receiver both see the movie of the peer they’re connected to:
Conclusion
In this tutorial you’ve learned about PeerJS and how you can use it to create real-time apps. Specifically we’ve created a messaging application that permits the user to send text and make a movie call to a remote peer. PeerJS is a indeed superb cross-browser way to implement WebRTC in web applications.
Don’t leave behind, the code used in this tutorial is available on GitHub. Clone it, make something cool and have joy!
Have you made something cool using PeerJS and/or WebRTC? Let me know in the comments below.
Building a WebRTC Movie Talk Application with PeerJS – SitePoint
Building a WebRTC Movie Talk Application with PeerJS
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 enlargening capacity of browsers to treat peer-to-peer communications in real-time, it’s lighter than ever to build real-time applications. In this tutorial we’ll take a look at PeerJS and how it can make our lives lighter when implementing WebRTC. Across this tutorial we’ll be building a WebRTC movie talk 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?
Before we stir on, it’s significant that we understand the main implement that we’ll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, movie, 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 effortless to use and understand which makes it a indeed superb candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn’t downright peer-to-peer. The reality is that there’s always a server which bridges the connection inbetween peers. Two or more devices can’t just magically create a connection out of skinny 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 permits 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 commenced 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 indeed work in production. This is because you can only have fifty concurrent connections and the server isn’t in HTTPS. The movie 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 movie or audio call features on your website then you will need the PeerJS server library. However, if you simply need a talk feature you can still use the PeerServer Cloud Service, provided your website doesn’t exceed the concurrent connection limit.
As we budge on through this tutorial I’ll be displaying you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Movie Talk App
Now it’s time to get our palms dirty by building the app. Very first we’re going to work with the client-side code and then we’ll stir 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 go after along at home, you will need to have Knot 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:
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event treating.
- 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:
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 duo of inline comments to highlight the significant points.
Take a 2nd 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.
Styling
The app only has minimal styling since most of the prettifying needs are already treated by Picnic. Our extra 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 movie. Let’s take a look at the code.
We embark off by proclaiming a duo 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 :
Next, we create a fresh PeerJS example 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 permits us to set the verbosity of the debug mode ( three being the highest) and the config option permits us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a Overwhelm or TURN server. You don’t truly 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 Numb or TURN server, you can look at this list of loosely available Overwhelm and TURN servers.
When the connection has been successfully initialized on the server, the open event is fired on the peer object. At this point the ID of the current user becomes available and we insert it into the page. This user can then give this ID to another user so that they can connect.
The next line adds a getUserMedia property to the navigator object, the value of which will be the flavor of getUserMedia in the browser. For WebKit browsers such as Chrome or Safari, this will be webkitGetUserMedia . For Firefox, this will be mozGetUserMedia . For other browsers which implement the UserMedia API, this will simply be getUserMedia . Note that this isn’t a fool-proof solution. You can use a shim such as getUserMedia.js if you want a more unified way to use the getUserMedia API.
Then comes a function for getting the current user’s movie feed. This uses the navigator.getUserMedia function which accepts three arguments:
- An object containing configuration options. In this case we set the audio and movie to true so both the camera and microphone in the device will work to provide a movie stream.
- A success callback function which we have specified as the argument for the getVideo function. Note that a stream will be passed as an argument into this anonymous callback function.
- An error callback function which simply alerts the user that an error has occurred.
The onReceiveStream function is responsible for initializing the movie stream;
Once the user clicks Log In, we use PeerJS to connect them with the user with the ID they have specified. The metadata object is used to pass in custom-made data to the peer. In this case we’re passing in the username so that we can display it on the peer’s side. Once the connection is established, the data event is triggered every time a message is sent to the current user. For convenience I’m going to refer to the current user (the one who initiates the connection) as User A, and the peer (the one who is being connected to) as User B.
When User A attempts to connect to User B, the connection event is triggered on User B’s peer object. This permits us to set the connection for User B and get the ID of User A ( connection.peer ). From that connection we can listen for the data event which is triggered whenever User A sends a message to User B. After that, we hide the peer ID text field, update its value to use the ID of the connecting peer and showcase the username of User A.
The handleMessage function accepts the data that was sent by the remote peer. This data is used to generate the HTML for the list of messages.
As you might imagine, the sendMessage function is used to send messages to a remote peer.
When a user initiates a call, we use the call method provided by the peer object to call the remote peer. The result of this function call comes back an object in which we can listen for the stream event. This event is fired when the movie feed of the remote peer becomes available to the user who initiated the call.
When the current user makes a call to a remote peer, the call event is triggered. From here we execute the onReceiveCall function to accept the call. If you want to add extra functionality for accepting a call, this is a good place to add it.
The onReceiveCall function accepts the current call object as its argument. The the call object’s response method is invoked to proceed with the call. This accepts the movie feed of the current user as its argument. When the movie feed of the remote peer becomes available, the stream event is triggered. From there we can call the onReceiveStream function to setup the remote peer’s movie.
The Server
Now we’re ready to proceed with the server. Very first, I’ll look at using the PeerServer Cloud Service, after which I’ll examine how to run your own PeerServer using peerjs-server.
Acquiring an API Key from the PeerServer Cloud Service
Go to peerjs.com and click on the Developer – Free button. This will open a modal window that will ask for your credentials. Pack out the form and click on the Accomplish Registration button. Once that’s done, you’ll be redirected to the dashboard page where you can see your API key.
Copy that and update the js/script.js file with your API key. You can liquidate the host , port and path properties from the configuration options in favour of a key property.
And that’s it. You can now hop to the demo section at the end of the article to see what the finished product looks like. Please bear in mind the limitations of this method (namely that you can only have fifty concurrent connections and that movie is not possible).
Running Your Own PeerServer
In this section I’ll walk you through how to run your own peer server.
This will have the following directory structure:
The server component is going to need the peerjs-server. You can install it by creating a package.json file in the root of the server directory and add the following:
Execute npm install to install the dependencies.
As we’re working locally, the server folder can go alongside your public folder in your project’s root directory (just as we have in our GitHub repo). If you’re not working locally, then the server folder will be on a remote server somewhere.
Creating the PeerServer
Inwards your working directory for the server component, create a peer-server.js file and add the following code:
What this does is create a PeerJS server that runs on port nine thousand . You can run the server by executing knot peer-server.js from the terminal. To check if the server is running, access http://localhost:9000/peerjs from the browser and you should see something similar to the following:
Deploying to a Remote Server
If you’re planning to deploy to a remote server later on, it has to be via HTTPS. This is because browsers only permits access to a device’s camera and microphone if the connection is secure. Here’s the code for the PeerServer to make it run on HTTPS:
This requires you to supply the key and certificate file that you acquired from your SSL certificate provider.
Running the App
To run the WebRTC movie talk app, you’ll need to have a server that will serve the files that we’ve created earlier on the client-side section. This is because the getUserMedia API won’t work by simply opening the index.html file on the browser. There are a entire bunch of ways to do this. Here are some of them:
Using PHP
If you have PHP installed on your machine, you can execute the following instruction while inwards the public directory to serve the files.
You can then access the app by going to: http://localhost:3000.
Using Apache
If you have Apache installed, you can copy the peer-messenger directory over to the root of your web folder and access the app using the following URL: http://localhost/public.
Using Knot
If you want to use Knot, you can install Express and have it serve the static files. You can install Express with the following directive:
Next, create an app-server.js file and add the following code:
You can then run the app by executing knot app-server.js . And you can access it by going to: http://localhost:3000.
Whichever method you choose, here’s what the app should look like:
From there the user can come in their username and the ID of the peer they’re attempting to connect to. For convenience let’s call this user the “initiator” because he is the one initiating the connection:
Once the initiator has logged in, peerJS sends the connection data to the peer. For convenience let’s call this user the “receiver”. Once the data is received on the receiver’s side, the screen is updated to demonstrate the username of the initiator.
The receiver can then come in their username and click on the Login button to begin talking to the initiator:
The initiator replies and clicks on the Call button:
Once the call goes through, the initiator and the receiver both see the movie of the peer they’re connected to:
Conclusion
In this tutorial you’ve learned about PeerJS and how you can use it to create real-time apps. Specifically we’ve created a messaging application that permits the user to send text and make a movie call to a remote peer. PeerJS is a truly fine cross-browser way to implement WebRTC in web applications.
Don’t leave behind, the code used in this tutorial is available on GitHub. Clone it, make something cool and have joy!
Have you made something cool using PeerJS and/or WebRTC? Let me know in the comments below.
Building a WebRTC Movie Talk Application with PeerJS – SitePoint
Building a WebRTC Movie Talk Application with PeerJS
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 enhancing capacity of browsers to treat peer-to-peer communications in real-time, it’s lighter than ever to build real-time applications. In this tutorial we’ll take a look at PeerJS and how it can make our lives lighter when implementing WebRTC. Via this tutorial we’ll be building a WebRTC movie talk 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?
Before we budge on, it’s significant that we understand the main device that we’ll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, movie, 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 effortless to use and understand which makes it a truly superb candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn’t entirely peer-to-peer. The reality is that there’s always a server which bridges the connection inbetween peers. Two or more devices can’t just magically create a connection out of lean 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 permits 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 embarked 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 truly work in production. This is because you can only have fifty concurrent connections and the server isn’t in HTTPS. The movie 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 movie or audio call features on your website then you will need the PeerJS server library. However, if you simply need a talk feature you can still use the PeerServer Cloud Service, provided your website doesn’t exceed the concurrent connection limit.
As we budge on through this tutorial I’ll be demonstrating you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Movie Talk App
Now it’s time to get our mitts dirty by building the app. Very first we’re going to work with the client-side code and then we’ll stir 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 go after along at home, you will need to have Knot 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:
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event treating.
- 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:
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 duo of inline comments to highlight the significant points.
Take a 2nd 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.
Styling
The app only has minimal styling since most of the prettifying needs are already treated by Picnic. Our extra 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 movie. Let’s take a look at the code.
We embark off by proclaiming a duo 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 :
Next, we create a fresh PeerJS example 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 permits us to set the verbosity of the debug mode ( three being the highest) and the config option permits us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a Overwhelm or TURN server. You don’t indeed 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 Numb or TURN server, you can look at this list of loosely available Numb and TURN servers.
When the connection has been successfully initialized on the server, the open event is fired on the peer object. At this point the ID of the current user becomes available and we insert it into the page. This user can then give this ID to another user so that they can connect.
The next line adds a getUserMedia property to the navigator object, the value of which will be the flavor of getUserMedia in the browser. For WebKit browsers such as Chrome or Safari, this will be webkitGetUserMedia . For Firefox, this will be mozGetUserMedia . For other browsers which implement the UserMedia API, this will simply be getUserMedia . Note that this isn’t a fool-proof solution. You can use a shim such as getUserMedia.js if you want a more unified way to use the getUserMedia API.
Then comes a function for getting the current user’s movie feed. This uses the navigator.getUserMedia function which accepts three arguments:
- An object containing configuration options. In this case we set the audio and movie to true so both the camera and microphone in the device will work to provide a movie stream.
- A success callback function which we have specified as the argument for the getVideo function. Note that a stream will be passed as an argument into this anonymous callback function.
- An error callback function which simply alerts the user that an error has occurred.
The onReceiveStream function is responsible for initializing the movie stream;
Once the user clicks Log In, we use PeerJS to connect them with the user with the ID they have specified. The metadata object is used to pass in custom-made data to the peer. In this case we’re passing in the username so that we can display it on the peer’s side. Once the connection is established, the data event is triggered every time a message is sent to the current user. For convenience I’m going to refer to the current user (the one who initiates the connection) as User A, and the peer (the one who is being connected to) as User B.
When User A attempts to connect to User B, the connection event is triggered on User B’s peer object. This permits us to set the connection for User B and get the ID of User A ( connection.peer ). From that connection we can listen for the data event which is triggered whenever User A sends a message to User B. After that, we hide the peer ID text field, update its value to use the ID of the connecting peer and showcase the username of User A.
The handleMessage function accepts the data that was sent by the remote peer. This data is used to generate the HTML for the list of messages.
As you might imagine, the sendMessage function is used to send messages to a remote peer.
When a user initiates a call, we use the call method provided by the peer object to call the remote peer. The result of this function call comes back an object in which we can listen for the stream event. This event is fired when the movie feed of the remote peer becomes available to the user who initiated the call.
When the current user makes a call to a remote peer, the call event is triggered. From here we execute the onReceiveCall function to accept the call. If you want to add extra functionality for accepting a call, this is a good place to add it.
The onReceiveCall function accepts the current call object as its argument. The the call object’s response method is invoked to proceed with the call. This accepts the movie feed of the current user as its argument. When the movie feed of the remote peer becomes available, the stream event is triggered. From there we can call the onReceiveStream function to setup the remote peer’s movie.
The Server
Now we’re ready to proceed with the server. Very first, I’ll look at using the PeerServer Cloud Service, after which I’ll examine how to run your own PeerServer using peerjs-server.
Acquiring an API Key from the PeerServer Cloud Service
Go to peerjs.com and click on the Developer – Free button. This will open a modal window that will ask for your credentials. Pack out the form and click on the Accomplish Registration button. Once that’s done, you’ll be redirected to the dashboard page where you can see your API key.
Copy that and update the js/script.js file with your API key. You can eliminate the host , port and path properties from the configuration options in favour of a key property.
And that’s it. You can now hop to the demo section at the end of the article to see what the finished product looks like. Please bear in mind the limitations of this method (namely that you can only have fifty concurrent connections and that movie is not possible).
Running Your Own PeerServer
In this section I’ll walk you through how to run your own peer server.
This will have the following directory structure:
The server component is going to need the peerjs-server. You can install it by creating a package.json file in the root of the server directory and add the following:
Execute npm install to install the dependencies.
As we’re working locally, the server folder can go alongside your public folder in your project’s root directory (just as we have in our GitHub repo). If you’re not working locally, then the server folder will be on a remote server somewhere.
Creating the PeerServer
Inwards your working directory for the server component, create a peer-server.js file and add the following code:
What this does is create a PeerJS server that runs on port nine thousand . You can run the server by executing knot peer-server.js from the terminal. To check if the server is running, access http://localhost:9000/peerjs from the browser and you should see something similar to the following:
Deploying to a Remote Server
If you’re planning to deploy to a remote server later on, it has to be via HTTPS. This is because browsers only permits access to a device’s camera and microphone if the connection is secure. Here’s the code for the PeerServer to make it run on HTTPS:
This requires you to supply the key and certificate file that you acquired from your SSL certificate provider.
Running the App
To run the WebRTC movie talk app, you’ll need to have a server that will serve the files that we’ve created earlier on the client-side section. This is because the getUserMedia API won’t work by simply opening the index.html file on the browser. There are a entire bunch of ways to do this. Here are some of them:
Using PHP
If you have PHP installed on your machine, you can execute the following directive while inwards the public directory to serve the files.
You can then access the app by going to: http://localhost:3000.
Using Apache
If you have Apache installed, you can copy the peer-messenger directory over to the root of your web folder and access the app using the following URL: http://localhost/public.
Using Knot
If you want to use Knot, you can install Express and have it serve the static files. You can install Express with the following guideline:
Next, create an app-server.js file and add the following code:
You can then run the app by executing knot app-server.js . And you can access it by going to: http://localhost:3000.
Whichever method you choose, here’s what the app should look like:
From there the user can inject their username and the ID of the peer they’re attempting to connect to. For convenience let’s call this user the “initiator” because he is the one initiating the connection:
Once the initiator has logged in, peerJS sends the connection data to the peer. For convenience let’s call this user the “receiver”. Once the data is received on the receiver’s side, the screen is updated to demonstrate the username of the initiator.
The receiver can then inject their username and click on the Login button to begin talking to the initiator:
The initiator replies and clicks on the Call button:
Once the call goes through, the initiator and the receiver both see the movie of the peer they’re connected to:
Conclusion
In this tutorial you’ve learned about PeerJS and how you can use it to create real-time apps. Specifically we’ve created a messaging application that permits the user to send text and make a movie call to a remote peer. PeerJS is a truly superb cross-browser way to implement WebRTC in web applications.
Don’t leave behind, the code used in this tutorial is available on GitHub. Clone it, make something cool and have joy!
Have you made something cool using PeerJS and/or WebRTC? Let me know in the comments below.
Building a WebRTC Movie Talk Application with PeerJS – SitePoint
Building a WebRTC Movie Talk Application with PeerJS
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 enhancing capacity of browsers to treat peer-to-peer communications in real-time, it’s lighter than ever to build real-time applications. In this tutorial we’ll take a look at PeerJS and how it can make our lives lighter when implementing WebRTC. Via this tutorial we’ll be building a WebRTC movie talk 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?
Before we stir on, it’s significant that we understand the main implement that we’ll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, movie, 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 effortless to use and understand which makes it a indeed good candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn’t totally peer-to-peer. The reality is that there’s always a server which bridges the connection inbetween peers. Two or more devices can’t just magically create a connection out of lean 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 permits 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 commenced 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 truly work in production. This is because you can only have fifty concurrent connections and the server isn’t in HTTPS. The movie 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 movie or audio call features on your website then you will need the PeerJS server library. However, if you simply need a talk feature you can still use the PeerServer Cloud Service, provided your website doesn’t exceed the concurrent connection limit.
As we budge on through this tutorial I’ll be displaying you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Movie Talk App
Now it’s time to get our forearms dirty by building the app. Very first we’re going to work with the client-side code and then we’ll stir 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 go after along at home, you will need to have Knot 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:
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event treating.
- 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:
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 duo of inline comments to highlight the significant points.
Take a 2nd 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.
Styling
The app only has minimal styling since most of the prettifying needs are already treated by Picnic. Our extra 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 movie. Let’s take a look at the code.
We begin off by proclaiming a duo 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 :
Next, we create a fresh PeerJS example 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 permits us to set the verbosity of the debug mode ( three being the highest) and the config option permits us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a Overwhelm or TURN server. You don’t truly 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 Overwhelm or TURN server, you can look at this list of loosely available Overwhelm and TURN servers.
When the connection has been successfully initialized on the server, the open event is fired on the peer object. At this point the ID of the current user becomes available and we insert it into the page. This user can then give this ID to another user so that they can connect.
The next line adds a getUserMedia property to the navigator object, the value of which will be the flavor of getUserMedia in the browser. For WebKit browsers such as Chrome or Safari, this will be webkitGetUserMedia . For Firefox, this will be mozGetUserMedia . For other browsers which implement the UserMedia API, this will simply be getUserMedia . Note that this isn’t a fool-proof solution. You can use a shim such as getUserMedia.js if you want a more unified way to use the getUserMedia API.
Then comes a function for getting the current user’s movie feed. This uses the navigator.getUserMedia function which accepts three arguments:
- An object containing configuration options. In this case we set the audio and movie to true so both the camera and microphone in the device will work to provide a movie stream.
- A success callback function which we have specified as the argument for the getVideo function. Note that a stream will be passed as an argument into this anonymous callback function.
- An error callback function which simply alerts the user that an error has occurred.
The onReceiveStream function is responsible for initializing the movie stream;
Once the user clicks Log In, we use PeerJS to connect them with the user with the ID they have specified. The metadata object is used to pass in custom-made data to the peer. In this case we’re passing in the username so that we can display it on the peer’s side. Once the connection is established, the data event is triggered every time a message is sent to the current user. For convenience I’m going to refer to the current user (the one who initiates the connection) as User A, and the peer (the one who is being connected to) as User B.
When User A attempts to connect to User B, the connection event is triggered on User B’s peer object. This permits us to set the connection for User B and get the ID of User A ( connection.peer ). From that connection we can listen for the data event which is triggered whenever User A sends a message to User B. After that, we hide the peer ID text field, update its value to use the ID of the connecting peer and display the username of User A.
The handleMessage function accepts the data that was sent by the remote peer. This data is used to generate the HTML for the list of messages.
As you might imagine, the sendMessage function is used to send messages to a remote peer.
When a user initiates a call, we use the call method provided by the peer object to call the remote peer. The result of this function call comes back an object in which we can listen for the stream event. This event is fired when the movie feed of the remote peer becomes available to the user who initiated the call.
When the current user makes a call to a remote peer, the call event is triggered. From here we execute the onReceiveCall function to accept the call. If you want to add extra functionality for accepting a call, this is a good place to add it.
The onReceiveCall function accepts the current call object as its argument. The the call object’s response method is invoked to proceed with the call. This accepts the movie feed of the current user as its argument. When the movie feed of the remote peer becomes available, the stream event is triggered. From there we can call the onReceiveStream function to setup the remote peer’s movie.
The Server
Now we’re ready to proceed with the server. Very first, I’ll look at using the PeerServer Cloud Service, after which I’ll examine how to run your own PeerServer using peerjs-server.
Acquiring an API Key from the PeerServer Cloud Service
Go to peerjs.com and click on the Developer – Free button. This will open a modal window that will ask for your credentials. Pack out the form and click on the Accomplish Registration button. Once that’s done, you’ll be redirected to the dashboard page where you can see your API key.
Copy that and update the js/script.js file with your API key. You can eliminate the host , port and path properties from the configuration options in favour of a key property.
And that’s it. You can now leap to the demo section at the end of the article to see what the finished product looks like. Please bear in mind the limitations of this method (namely that you can only have fifty concurrent connections and that movie is not possible).
Running Your Own PeerServer
In this section I’ll walk you through how to run your own peer server.
This will have the following directory structure:
The server component is going to need the peerjs-server. You can install it by creating a package.json file in the root of the server directory and add the following:
Execute npm install to install the dependencies.
As we’re working locally, the server folder can go alongside your public folder in your project’s root directory (just as we have in our GitHub repo). If you’re not working locally, then the server folder will be on a remote server somewhere.
Creating the PeerServer
Inwards your working directory for the server component, create a peer-server.js file and add the following code:
What this does is create a PeerJS server that runs on port nine thousand . You can run the server by executing knot peer-server.js from the terminal. To check if the server is running, access http://localhost:9000/peerjs from the browser and you should see something similar to the following:
Deploying to a Remote Server
If you’re planning to deploy to a remote server later on, it has to be via HTTPS. This is because browsers only permits access to a device’s camera and microphone if the connection is secure. Here’s the code for the PeerServer to make it run on HTTPS:
This requires you to supply the key and certificate file that you acquired from your SSL certificate provider.
Running the App
To run the WebRTC movie talk app, you’ll need to have a server that will serve the files that we’ve created earlier on the client-side section. This is because the getUserMedia API won’t work by simply opening the index.html file on the browser. There are a entire bunch of ways to do this. Here are some of them:
Using PHP
If you have PHP installed on your machine, you can execute the following directive while inwards the public directory to serve the files.
You can then access the app by going to: http://localhost:3000.
Using Apache
If you have Apache installed, you can copy the peer-messenger directory over to the root of your web folder and access the app using the following URL: http://localhost/public.
Using Knot
If you want to use Knot, you can install Express and have it serve the static files. You can install Express with the following instruction:
Next, create an app-server.js file and add the following code:
You can then run the app by executing knot app-server.js . And you can access it by going to: http://localhost:3000.
Whichever method you choose, here’s what the app should look like:
From there the user can come in their username and the ID of the peer they’re attempting to connect to. For convenience let’s call this user the “initiator” because he is the one initiating the connection:
Once the initiator has logged in, peerJS sends the connection data to the peer. For convenience let’s call this user the “receiver”. Once the data is received on the receiver’s side, the screen is updated to showcase the username of the initiator.
The receiver can then inject their username and click on the Login button to begin talking to the initiator:
The initiator replies and clicks on the Call button:
Once the call goes through, the initiator and the receiver both see the movie of the peer they’re connected to:
Conclusion
In this tutorial you’ve learned about PeerJS and how you can use it to create real-time apps. Specifically we’ve created a messaging application that permits the user to send text and make a movie call to a remote peer. PeerJS is a truly good cross-browser way to implement WebRTC in web applications.
Don’t leave behind, the code used in this tutorial is available on GitHub. Clone it, make something cool and have joy!
Have you made something cool using PeerJS and/or WebRTC? Let me know in the comments below.
Building a WebRTC Movie Talk Application with PeerJS – SitePoint
Building a WebRTC Movie Talk Application with PeerJS
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 enhancing capacity of browsers to treat peer-to-peer communications in real-time, it’s lighter than ever to build real-time applications. In this tutorial we’ll take a look at PeerJS and how it can make our lives lighter when implementing WebRTC. Across this tutorial we’ll be building a WebRTC movie talk 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?
Before we budge on, it’s significant that we understand the main instrument that we’ll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, movie, 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 effortless to use and understand which makes it a truly fine candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn’t downright peer-to-peer. The reality is that there’s always a server which bridges the connection inbetween peers. Two or more devices can’t just magically create a connection out of lean 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 permits 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 began 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 indeed work in production. This is because you can only have fifty concurrent connections and the server isn’t in HTTPS. The movie 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 movie or audio call features on your website then you will need the PeerJS server library. However, if you simply need a talk feature you can still use the PeerServer Cloud Service, provided your website doesn’t exceed the concurrent connection limit.
As we budge on through this tutorial I’ll be showcasing you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Movie Talk App
Now it’s time to get our forearms dirty by building the app. Very first we’re going to work with the client-side code and then we’ll budge 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 go after along at home, you will need to have Knot 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:
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event treating.
- 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:
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 duo of inline comments to highlight the significant points.
Take a 2nd 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.
Styling
The app only has minimal styling since most of the prettifying needs are already treated by Picnic. Our extra 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 movie. Let’s take a look at the code.
We embark off by announcing a duo 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 :
Next, we create a fresh PeerJS example 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 permits us to set the verbosity of the debug mode ( three being the highest) and the config option permits us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a Numb or TURN server. You don’t indeed 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 Numb or TURN server, you can look at this list of loosely available Numb and TURN servers.
When the connection has been successfully initialized on the server, the open event is fired on the peer object. At this point the ID of the current user becomes available and we insert it into the page. This user can then give this ID to another user so that they can connect.
The next line adds a getUserMedia property to the navigator object, the value of which will be the flavor of getUserMedia in the browser. For WebKit browsers such as Chrome or Safari, this will be webkitGetUserMedia . For Firefox, this will be mozGetUserMedia . For other browsers which implement the UserMedia API, this will simply be getUserMedia . Note that this isn’t a fool-proof solution. You can use a shim such as getUserMedia.js if you want a more unified way to use the getUserMedia API.
Then comes a function for getting the current user’s movie feed. This uses the navigator.getUserMedia function which accepts three arguments:
- An object containing configuration options. In this case we set the audio and movie to true so both the camera and microphone in the device will work to provide a movie stream.
- A success callback function which we have specified as the argument for the getVideo function. Note that a stream will be passed as an argument into this anonymous callback function.
- An error callback function which simply alerts the user that an error has occurred.
The onReceiveStream function is responsible for initializing the movie stream;
Once the user clicks Log In, we use PeerJS to connect them with the user with the ID they have specified. The metadata object is used to pass in custom-built data to the peer. In this case we’re passing in the username so that we can display it on the peer’s side. Once the connection is established, the data event is triggered every time a message is sent to the current user. For convenience I’m going to refer to the current user (the one who initiates the connection) as User A, and the peer (the one who is being connected to) as User B.
When User A attempts to connect to User B, the connection event is triggered on User B’s peer object. This permits us to set the connection for User B and get the ID of User A ( connection.peer ). From that connection we can listen for the data event which is triggered whenever User A sends a message to User B. After that, we hide the peer ID text field, update its value to use the ID of the connecting peer and demonstrate the username of User A.
The handleMessage function accepts the data that was sent by the remote peer. This data is used to generate the HTML for the list of messages.
As you might imagine, the sendMessage function is used to send messages to a remote peer.
When a user initiates a call, we use the call method provided by the peer object to call the remote peer. The result of this function call comes back an object in which we can listen for the stream event. This event is fired when the movie feed of the remote peer becomes available to the user who initiated the call.
When the current user makes a call to a remote peer, the call event is triggered. From here we execute the onReceiveCall function to accept the call. If you want to add extra functionality for accepting a call, this is a good place to add it.
The onReceiveCall function accepts the current call object as its argument. The the call object’s response method is invoked to proceed with the call. This accepts the movie feed of the current user as its argument. When the movie feed of the remote peer becomes available, the stream event is triggered. From there we can call the onReceiveStream function to setup the remote peer’s movie.
The Server
Now we’re ready to proceed with the server. Very first, I’ll look at using the PeerServer Cloud Service, after which I’ll examine how to run your own PeerServer using peerjs-server.
Acquiring an API Key from the PeerServer Cloud Service
Go to peerjs.com and click on the Developer – Free button. This will open a modal window that will ask for your credentials. Pack out the form and click on the Accomplish Registration button. Once that’s done, you’ll be redirected to the dashboard page where you can see your API key.
Copy that and update the js/script.js file with your API key. You can liquidate the host , port and path properties from the configuration options in favour of a key property.
And that’s it. You can now leap to the demo section at the end of the article to see what the finished product looks like. Please bear in mind the limitations of this method (namely that you can only have fifty concurrent connections and that movie is not possible).
Running Your Own PeerServer
In this section I’ll walk you through how to run your own peer server.
This will have the following directory structure:
The server component is going to need the peerjs-server. You can install it by creating a package.json file in the root of the server directory and add the following:
Execute npm install to install the dependencies.
As we’re working locally, the server folder can go alongside your public folder in your project’s root directory (just as we have in our GitHub repo). If you’re not working locally, then the server folder will be on a remote server somewhere.
Creating the PeerServer
Inwards your working directory for the server component, create a peer-server.js file and add the following code:
What this does is create a PeerJS server that runs on port nine thousand . You can run the server by executing knot peer-server.js from the terminal. To check if the server is running, access http://localhost:9000/peerjs from the browser and you should see something similar to the following:
Deploying to a Remote Server
If you’re planning to deploy to a remote server later on, it has to be via HTTPS. This is because browsers only permits access to a device’s camera and microphone if the connection is secure. Here’s the code for the PeerServer to make it run on HTTPS:
This requires you to supply the key and certificate file that you acquired from your SSL certificate provider.
Running the App
To run the WebRTC movie talk app, you’ll need to have a server that will serve the files that we’ve created earlier on the client-side section. This is because the getUserMedia API won’t work by simply opening the index.html file on the browser. There are a entire bunch of ways to do this. Here are some of them:
Using PHP
If you have PHP installed on your machine, you can execute the following directive while inwards the public directory to serve the files.
You can then access the app by going to: http://localhost:3000.
Using Apache
If you have Apache installed, you can copy the peer-messenger directory over to the root of your web folder and access the app using the following URL: http://localhost/public.
Using Knot
If you want to use Knot, you can install Express and have it serve the static files. You can install Express with the following guideline:
Next, create an app-server.js file and add the following code:
You can then run the app by executing knot app-server.js . And you can access it by going to: http://localhost:3000.
Whichever method you choose, here’s what the app should look like:
From there the user can inject their username and the ID of the peer they’re attempting to connect to. For convenience let’s call this user the “initiator” because he is the one initiating the connection:
Once the initiator has logged in, peerJS sends the connection data to the peer. For convenience let’s call this user the “receiver”. Once the data is received on the receiver’s side, the screen is updated to showcase the username of the initiator.
The receiver can then come in their username and click on the Login button to begin talking to the initiator:
The initiator replies and clicks on the Call button:
Once the call goes through, the initiator and the receiver both see the movie of the peer they’re connected to:
Conclusion
In this tutorial you’ve learned about PeerJS and how you can use it to create real-time apps. Specifically we’ve created a messaging application that permits the user to send text and make a movie call to a remote peer. PeerJS is a indeed good cross-browser way to implement WebRTC in web applications.
Don’t leave behind, the code used in this tutorial is available on GitHub. Clone it, make something cool and have joy!
Have you made something cool using PeerJS and/or WebRTC? Let me know in the comments below.
Building a WebRTC Movie Talk Application with PeerJS – SitePoint
Building a WebRTC Movie Talk Application with PeerJS
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 enhancing capacity of browsers to treat peer-to-peer communications in real-time, it’s lighter than ever to build real-time applications. In this tutorial we’ll take a look at PeerJS and how it can make our lives lighter when implementing WebRTC. Across this tutorial we’ll be building a WebRTC movie talk 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?
Before we budge on, it’s significant that we understand the main contraption that we’ll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, movie, 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 effortless to use and understand which makes it a truly superb candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn’t downright peer-to-peer. The reality is that there’s always a server which bridges the connection inbetween peers. Two or more devices can’t just magically create a connection out of skinny 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 permits 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 began 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 truly work in production. This is because you can only have fifty concurrent connections and the server isn’t in HTTPS. The movie 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 movie or audio call features on your website then you will need the PeerJS server library. However, if you simply need a talk feature you can still use the PeerServer Cloud Service, provided your website doesn’t exceed the concurrent connection limit.
As we budge on through this tutorial I’ll be displaying you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Movie Talk App
Now it’s time to get our forearms dirty by building the app. Very first we’re going to work with the client-side code and then we’ll stir 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 go after along at home, you will need to have Knot 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:
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event treating.
- 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:
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 duo of inline comments to highlight the significant points.
Take a 2nd 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.
Styling
The app only has minimal styling since most of the prettifying needs are already treated by Picnic. Our extra 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 movie. Let’s take a look at the code.
We commence off by proclaiming a duo 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 :
Next, we create a fresh PeerJS example 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 permits us to set the verbosity of the debug mode ( three being the highest) and the config option permits us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a Overwhelm or TURN server. You don’t truly 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 Numb or TURN server, you can look at this list of loosely available Numb and TURN servers.
When the connection has been successfully initialized on the server, the open event is fired on the peer object. At this point the ID of the current user becomes available and we insert it into the page. This user can then give this ID to another user so that they can connect.
The next line adds a getUserMedia property to the navigator object, the value of which will be the flavor of getUserMedia in the browser. For WebKit browsers such as Chrome or Safari, this will be webkitGetUserMedia . For Firefox, this will be mozGetUserMedia . For other browsers which implement the UserMedia API, this will simply be getUserMedia . Note that this isn’t a fool-proof solution. You can use a shim such as getUserMedia.js if you want a more unified way to use the getUserMedia API.
Then comes a function for getting the current user’s movie feed. This uses the navigator.getUserMedia function which accepts three arguments:
- An object containing configuration options. In this case we set the audio and movie to true so both the camera and microphone in the device will work to provide a movie stream.
- A success callback function which we have specified as the argument for the getVideo function. Note that a stream will be passed as an argument into this anonymous callback function.
- An error callback function which simply alerts the user that an error has occurred.
The onReceiveStream function is responsible for initializing the movie stream;
Once the user clicks Log In, we use PeerJS to connect them with the user with the ID they have specified. The metadata object is used to pass in custom-made data to the peer. In this case we’re passing in the username so that we can display it on the peer’s side. Once the connection is established, the data event is triggered every time a message is sent to the current user. For convenience I’m going to refer to the current user (the one who initiates the connection) as User A, and the peer (the one who is being connected to) as User B.
When User A attempts to connect to User B, the connection event is triggered on User B’s peer object. This permits us to set the connection for User B and get the ID of User A ( connection.peer ). From that connection we can listen for the data event which is triggered whenever User A sends a message to User B. After that, we hide the peer ID text field, update its value to use the ID of the connecting peer and demonstrate the username of User A.
The handleMessage function accepts the data that was sent by the remote peer. This data is used to generate the HTML for the list of messages.
As you might imagine, the sendMessage function is used to send messages to a remote peer.
When a user initiates a call, we use the call method provided by the peer object to call the remote peer. The result of this function call comebacks an object in which we can listen for the stream event. This event is fired when the movie feed of the remote peer becomes available to the user who initiated the call.
When the current user makes a call to a remote peer, the call event is triggered. From here we execute the onReceiveCall function to accept the call. If you want to add extra functionality for accepting a call, this is a good place to add it.
The onReceiveCall function accepts the current call object as its argument. The the call object’s response method is invoked to proceed with the call. This accepts the movie feed of the current user as its argument. When the movie feed of the remote peer becomes available, the stream event is triggered. From there we can call the onReceiveStream function to setup the remote peer’s movie.
The Server
Now we’re ready to proceed with the server. Very first, I’ll look at using the PeerServer Cloud Service, after which I’ll examine how to run your own PeerServer using peerjs-server.
Acquiring an API Key from the PeerServer Cloud Service
Go to peerjs.com and click on the Developer – Free button. This will open a modal window that will ask for your credentials. Pack out the form and click on the Accomplish Registration button. Once that’s done, you’ll be redirected to the dashboard page where you can see your API key.
Copy that and update the js/script.js file with your API key. You can eliminate the host , port and path properties from the configuration options in favour of a key property.
And that’s it. You can now hop to the demo section at the end of the article to see what the finished product looks like. Please bear in mind the limitations of this method (namely that you can only have fifty concurrent connections and that movie is not possible).
Running Your Own PeerServer
In this section I’ll walk you through how to run your own peer server.
This will have the following directory structure:
The server component is going to need the peerjs-server. You can install it by creating a package.json file in the root of the server directory and add the following:
Execute npm install to install the dependencies.
As we’re working locally, the server folder can go alongside your public folder in your project’s root directory (just as we have in our GitHub repo). If you’re not working locally, then the server folder will be on a remote server somewhere.
Creating the PeerServer
Inwards your working directory for the server component, create a peer-server.js file and add the following code:
What this does is create a PeerJS server that runs on port nine thousand . You can run the server by executing knot peer-server.js from the terminal. To check if the server is running, access http://localhost:9000/peerjs from the browser and you should see something similar to the following:
Deploying to a Remote Server
If you’re planning to deploy to a remote server later on, it has to be via HTTPS. This is because browsers only permits access to a device’s camera and microphone if the connection is secure. Here’s the code for the PeerServer to make it run on HTTPS:
This requires you to supply the key and certificate file that you acquired from your SSL certificate provider.
Running the App
To run the WebRTC movie talk app, you’ll need to have a server that will serve the files that we’ve created earlier on the client-side section. This is because the getUserMedia API won’t work by simply opening the index.html file on the browser. There are a entire bunch of ways to do this. Here are some of them:
Using PHP
If you have PHP installed on your machine, you can execute the following directive while inwards the public directory to serve the files.
You can then access the app by going to: http://localhost:3000.
Using Apache
If you have Apache installed, you can copy the peer-messenger directory over to the root of your web folder and access the app using the following URL: http://localhost/public.
Using Knot
If you want to use Knot, you can install Express and have it serve the static files. You can install Express with the following directive:
Next, create an app-server.js file and add the following code:
You can then run the app by executing knot app-server.js . And you can access it by going to: http://localhost:3000.
Whichever method you choose, here’s what the app should look like:
From there the user can come in their username and the ID of the peer they’re attempting to connect to. For convenience let’s call this user the “initiator” because he is the one initiating the connection:
Once the initiator has logged in, peerJS sends the connection data to the peer. For convenience let’s call this user the “receiver”. Once the data is received on the receiver’s side, the screen is updated to showcase the username of the initiator.
The receiver can then inject their username and click on the Login button to begin talking to the initiator:
The initiator replies and clicks on the Call button:
Once the call goes through, the initiator and the receiver both see the movie of the peer they’re connected to:
Conclusion
In this tutorial you’ve learned about PeerJS and how you can use it to create real-time apps. Specifically we’ve created a messaging application that permits the user to send text and make a movie call to a remote peer. PeerJS is a indeed superb cross-browser way to implement WebRTC in web applications.
Don’t leave behind, the code used in this tutorial is available on GitHub. Clone it, make something cool and have joy!
Have you made something cool using PeerJS and/or WebRTC? Let me know in the comments below.
Building a WebRTC Movie Talk Application with PeerJS – SitePoint
Building a WebRTC Movie Talk Application with PeerJS
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 enhancing capacity of browsers to treat peer-to-peer communications in real-time, it’s lighter than ever to build real-time applications. In this tutorial we’ll take a look at PeerJS and how it can make our lives lighter when implementing WebRTC. Via this tutorial we’ll be building a WebRTC movie talk 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?
Before we stir on, it’s significant that we understand the main contraption that we’ll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, movie, 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 effortless to use and understand which makes it a indeed good candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn’t entirely peer-to-peer. The reality is that there’s always a server which bridges the connection inbetween peers. Two or more devices can’t just magically create a connection out of skinny 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 permits 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 embarked 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 truly work in production. This is because you can only have fifty concurrent connections and the server isn’t in HTTPS. The movie 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 movie or audio call features on your website then you will need the PeerJS server library. However, if you simply need a talk feature you can still use the PeerServer Cloud Service, provided your website doesn’t exceed the concurrent connection limit.
As we budge on through this tutorial I’ll be displaying you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Movie Talk App
Now it’s time to get our palms dirty by building the app. Very first we’re going to work with the client-side code and then we’ll budge 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 go after along at home, you will need to have Knot 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:
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event treating.
- 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:
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 duo of inline comments to highlight the significant points.
Take a 2nd 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.
Styling
The app only has minimal styling since most of the prettifying needs are already treated by Picnic. Our extra 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 movie. Let’s take a look at the code.
We commence off by announcing a duo 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 :
Next, we create a fresh PeerJS example 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 permits us to set the verbosity of the debug mode ( three being the highest) and the config option permits us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a Numb or TURN server. You don’t indeed 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 Numb or TURN server, you can look at this list of loosely available Numb and TURN servers.
When the connection has been successfully initialized on the server, the open event is fired on the peer object. At this point the ID of the current user becomes available and we insert it into the page. This user can then give this ID to another user so that they can connect.
The next line adds a getUserMedia property to the navigator object, the value of which will be the flavor of getUserMedia in the browser. For WebKit browsers such as Chrome or Safari, this will be webkitGetUserMedia . For Firefox, this will be mozGetUserMedia . For other browsers which implement the UserMedia API, this will simply be getUserMedia . Note that this isn’t a fool-proof solution. You can use a shim such as getUserMedia.js if you want a more unified way to use the getUserMedia API.
Then comes a function for getting the current user’s movie feed. This uses the navigator.getUserMedia function which accepts three arguments:
- An object containing configuration options. In this case we set the audio and movie to true so both the camera and microphone in the device will work to provide a movie stream.
- A success callback function which we have specified as the argument for the getVideo function. Note that a stream will be passed as an argument into this anonymous callback function.
- An error callback function which simply alerts the user that an error has occurred.
The onReceiveStream function is responsible for initializing the movie stream;
Once the user clicks Log In, we use PeerJS to connect them with the user with the ID they have specified. The metadata object is used to pass in custom-made data to the peer. In this case we’re passing in the username so that we can display it on the peer’s side. Once the connection is established, the data event is triggered every time a message is sent to the current user. For convenience I’m going to refer to the current user (the one who initiates the connection) as User A, and the peer (the one who is being connected to) as User B.
When User A attempts to connect to User B, the connection event is triggered on User B’s peer object. This permits us to set the connection for User B and get the ID of User A ( connection.peer ). From that connection we can listen for the data event which is triggered whenever User A sends a message to User B. After that, we hide the peer ID text field, update its value to use the ID of the connecting peer and display the username of User A.
The handleMessage function accepts the data that was sent by the remote peer. This data is used to generate the HTML for the list of messages.
As you might imagine, the sendMessage function is used to send messages to a remote peer.
When a user initiates a call, we use the call method provided by the peer object to call the remote peer. The result of this function call comes back an object in which we can listen for the stream event. This event is fired when the movie feed of the remote peer becomes available to the user who initiated the call.
When the current user makes a call to a remote peer, the call event is triggered. From here we execute the onReceiveCall function to accept the call. If you want to add extra functionality for accepting a call, this is a good place to add it.
The onReceiveCall function accepts the current call object as its argument. The the call object’s reaction method is invoked to proceed with the call. This accepts the movie feed of the current user as its argument. When the movie feed of the remote peer becomes available, the stream event is triggered. From there we can call the onReceiveStream function to setup the remote peer’s movie.
The Server
Now we’re ready to proceed with the server. Very first, I’ll look at using the PeerServer Cloud Service, after which I’ll examine how to run your own PeerServer using peerjs-server.
Acquiring an API Key from the PeerServer Cloud Service
Go to peerjs.com and click on the Developer – Free button. This will open a modal window that will ask for your credentials. Pack out the form and click on the Accomplish Registration button. Once that’s done, you’ll be redirected to the dashboard page where you can see your API key.
Copy that and update the js/script.js file with your API key. You can liquidate the host , port and path properties from the configuration options in favour of a key property.
And that’s it. You can now hop to the demo section at the end of the article to see what the finished product looks like. Please bear in mind the limitations of this method (namely that you can only have fifty concurrent connections and that movie is not possible).
Running Your Own PeerServer
In this section I’ll walk you through how to run your own peer server.
This will have the following directory structure:
The server component is going to need the peerjs-server. You can install it by creating a package.json file in the root of the server directory and add the following:
Execute npm install to install the dependencies.
As we’re working locally, the server folder can go alongside your public folder in your project’s root directory (just as we have in our GitHub repo). If you’re not working locally, then the server folder will be on a remote server somewhere.
Creating the PeerServer
Inwards your working directory for the server component, create a peer-server.js file and add the following code:
What this does is create a PeerJS server that runs on port nine thousand . You can run the server by executing knot peer-server.js from the terminal. To check if the server is running, access http://localhost:9000/peerjs from the browser and you should see something similar to the following:
Deploying to a Remote Server
If you’re planning to deploy to a remote server later on, it has to be via HTTPS. This is because browsers only permits access to a device’s camera and microphone if the connection is secure. Here’s the code for the PeerServer to make it run on HTTPS:
This requires you to supply the key and certificate file that you acquired from your SSL certificate provider.
Running the App
To run the WebRTC movie talk app, you’ll need to have a server that will serve the files that we’ve created earlier on the client-side section. This is because the getUserMedia API won’t work by simply opening the index.html file on the browser. There are a entire bunch of ways to do this. Here are some of them:
Using PHP
If you have PHP installed on your machine, you can execute the following instruction while inwards the public directory to serve the files.
You can then access the app by going to: http://localhost:3000.
Using Apache
If you have Apache installed, you can copy the peer-messenger directory over to the root of your web folder and access the app using the following URL: http://localhost/public.
Using Knot
If you want to use Knot, you can install Express and have it serve the static files. You can install Express with the following directive:
Next, create an app-server.js file and add the following code:
You can then run the app by executing knot app-server.js . And you can access it by going to: http://localhost:3000.
Whichever method you choose, here’s what the app should look like:
From there the user can come in their username and the ID of the peer they’re attempting to connect to. For convenience let’s call this user the “initiator” because he is the one initiating the connection:
Once the initiator has logged in, peerJS sends the connection data to the peer. For convenience let’s call this user the “receiver”. Once the data is received on the receiver’s side, the screen is updated to demonstrate the username of the initiator.
The receiver can then come in their username and click on the Login button to begin talking to the initiator:
The initiator replies and clicks on the Call button:
Once the call goes through, the initiator and the receiver both see the movie of the peer they’re connected to:
Conclusion
In this tutorial you’ve learned about PeerJS and how you can use it to create real-time apps. Specifically we’ve created a messaging application that permits the user to send text and make a movie call to a remote peer. PeerJS is a truly excellent cross-browser way to implement WebRTC in web applications.
Don’t leave behind, the code used in this tutorial is available on GitHub. Clone it, make something cool and have joy!
Have you made something cool using PeerJS and/or WebRTC? Let me know in the comments below.
Building a WebRTC Movie Talk Application with PeerJS – SitePoint
Building a WebRTC Movie Talk Application with PeerJS
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 enlargening capacity of browsers to treat peer-to-peer communications in real-time, it’s lighter than ever to build real-time applications. In this tutorial we’ll take a look at PeerJS and how it can make our lives lighter when implementing WebRTC. Via this tutorial we’ll be building a WebRTC movie talk 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?
Before we budge on, it’s significant that we understand the main contraption that we’ll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, movie, 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 effortless to use and understand which makes it a truly good candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn’t fully peer-to-peer. The reality is that there’s always a server which bridges the connection inbetween peers. Two or more devices can’t just magically create a connection out of skinny 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 permits 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 embarked 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 indeed work in production. This is because you can only have fifty concurrent connections and the server isn’t in HTTPS. The movie 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 movie or audio call features on your website then you will need the PeerJS server library. However, if you simply need a talk feature you can still use the PeerServer Cloud Service, provided your website doesn’t exceed the concurrent connection limit.
As we budge on through this tutorial I’ll be displaying you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Movie Talk App
Now it’s time to get our palms dirty by building the app. Very first we’re going to work with the client-side code and then we’ll stir 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 go after along at home, you will need to have Knot 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:
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event treating.
- 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:
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 duo of inline comments to highlight the significant points.
Take a 2nd 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.
Styling
The app only has minimal styling since most of the prettifying needs are already treated by Picnic. Our extra 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 movie. Let’s take a look at the code.
We begin off by announcing a duo 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 :
Next, we create a fresh PeerJS example 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 permits us to set the verbosity of the debug mode ( three being the highest) and the config option permits us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a Numb or TURN server. You don’t truly 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 Overwhelm or TURN server, you can look at this list of loosely available Numb and TURN servers.
When the connection has been successfully initialized on the server, the open event is fired on the peer object. At this point the ID of the current user becomes available and we insert it into the page. This user can then give this ID to another user so that they can connect.
The next line adds a getUserMedia property to the navigator object, the value of which will be the flavor of getUserMedia in the browser. For WebKit browsers such as Chrome or Safari, this will be webkitGetUserMedia . For Firefox, this will be mozGetUserMedia . For other browsers which implement the UserMedia API, this will simply be getUserMedia . Note that this isn’t a fool-proof solution. You can use a shim such as getUserMedia.js if you want a more unified way to use the getUserMedia API.
Then comes a function for getting the current user’s movie feed. This uses the navigator.getUserMedia function which accepts three arguments:
- An object containing configuration options. In this case we set the audio and movie to true so both the camera and microphone in the device will work to provide a movie stream.
- A success callback function which we have specified as the argument for the getVideo function. Note that a stream will be passed as an argument into this anonymous callback function.
- An error callback function which simply alerts the user that an error has occurred.
The onReceiveStream function is responsible for initializing the movie stream;
Once the user clicks Log In, we use PeerJS to connect them with the user with the ID they have specified. The metadata object is used to pass in custom-built data to the peer. In this case we’re passing in the username so that we can display it on the peer’s side. Once the connection is established, the data event is triggered every time a message is sent to the current user. For convenience I’m going to refer to the current user (the one who initiates the connection) as User A, and the peer (the one who is being connected to) as User B.
When User A attempts to connect to User B, the connection event is triggered on User B’s peer object. This permits us to set the connection for User B and get the ID of User A ( connection.peer ). From that connection we can listen for the data event which is triggered whenever User A sends a message to User B. After that, we hide the peer ID text field, update its value to use the ID of the connecting peer and showcase the username of User A.
The handleMessage function accepts the data that was sent by the remote peer. This data is used to generate the HTML for the list of messages.
As you might imagine, the sendMessage function is used to send messages to a remote peer.
When a user initiates a call, we use the call method provided by the peer object to call the remote peer. The result of this function call comebacks an object in which we can listen for the stream event. This event is fired when the movie feed of the remote peer becomes available to the user who initiated the call.
When the current user makes a call to a remote peer, the call event is triggered. From here we execute the onReceiveCall function to accept the call. If you want to add extra functionality for accepting a call, this is a good place to add it.
The onReceiveCall function accepts the current call object as its argument. The the call object’s response method is invoked to proceed with the call. This accepts the movie feed of the current user as its argument. When the movie feed of the remote peer becomes available, the stream event is triggered. From there we can call the onReceiveStream function to setup the remote peer’s movie.
The Server
Now we’re ready to proceed with the server. Very first, I’ll look at using the PeerServer Cloud Service, after which I’ll examine how to run your own PeerServer using peerjs-server.
Acquiring an API Key from the PeerServer Cloud Service
Go to peerjs.com and click on the Developer – Free button. This will open a modal window that will ask for your credentials. Pack out the form and click on the Accomplish Registration button. Once that’s done, you’ll be redirected to the dashboard page where you can see your API key.
Copy that and update the js/script.js file with your API key. You can liquidate the host , port and path properties from the configuration options in favour of a key property.
And that’s it. You can now hop to the demo section at the end of the article to see what the finished product looks like. Please bear in mind the limitations of this method (namely that you can only have fifty concurrent connections and that movie is not possible).
Running Your Own PeerServer
In this section I’ll walk you through how to run your own peer server.
This will have the following directory structure:
The server component is going to need the peerjs-server. You can install it by creating a package.json file in the root of the server directory and add the following:
Execute npm install to install the dependencies.
As we’re working locally, the server folder can go alongside your public folder in your project’s root directory (just as we have in our GitHub repo). If you’re not working locally, then the server folder will be on a remote server somewhere.
Creating the PeerServer
Inwards your working directory for the server component, create a peer-server.js file and add the following code:
What this does is create a PeerJS server that runs on port nine thousand . You can run the server by executing knot peer-server.js from the terminal. To check if the server is running, access http://localhost:9000/peerjs from the browser and you should see something similar to the following:
Deploying to a Remote Server
If you’re planning to deploy to a remote server later on, it has to be via HTTPS. This is because browsers only permits access to a device’s camera and microphone if the connection is secure. Here’s the code for the PeerServer to make it run on HTTPS:
This requires you to supply the key and certificate file that you acquired from your SSL certificate provider.
Running the App
To run the WebRTC movie talk app, you’ll need to have a server that will serve the files that we’ve created earlier on the client-side section. This is because the getUserMedia API won’t work by simply opening the index.html file on the browser. There are a entire bunch of ways to do this. Here are some of them:
Using PHP
If you have PHP installed on your machine, you can execute the following directive while inwards the public directory to serve the files.
You can then access the app by going to: http://localhost:3000.
Using Apache
If you have Apache installed, you can copy the peer-messenger directory over to the root of your web folder and access the app using the following URL: http://localhost/public.
Using Knot
If you want to use Knot, you can install Express and have it serve the static files. You can install Express with the following instruction:
Next, create an app-server.js file and add the following code:
You can then run the app by executing knot app-server.js . And you can access it by going to: http://localhost:3000.
Whichever method you choose, here’s what the app should look like:
From there the user can inject their username and the ID of the peer they’re attempting to connect to. For convenience let’s call this user the “initiator” because he is the one initiating the connection:
Once the initiator has logged in, peerJS sends the connection data to the peer. For convenience let’s call this user the “receiver”. Once the data is received on the receiver’s side, the screen is updated to demonstrate the username of the initiator.
The receiver can then inject their username and click on the Login button to begin talking to the initiator:
The initiator replies and clicks on the Call button:
Once the call goes through, the initiator and the receiver both see the movie of the peer they’re connected to:
Conclusion
In this tutorial you’ve learned about PeerJS and how you can use it to create real-time apps. Specifically we’ve created a messaging application that permits the user to send text and make a movie call to a remote peer. PeerJS is a indeed excellent cross-browser way to implement WebRTC in web applications.
Don’t leave behind, the code used in this tutorial is available on GitHub. Clone it, make something cool and have joy!
Have you made something cool using PeerJS and/or WebRTC? Let me know in the comments below.
Building a WebRTC Movie Talk Application with PeerJS – SitePoint
Building a WebRTC Movie Talk Application with PeerJS
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 enlargening capacity of browsers to treat peer-to-peer communications in real-time, it’s lighter than ever to build real-time applications. In this tutorial we’ll take a look at PeerJS and how it can make our lives lighter when implementing WebRTC. Via this tutorial we’ll be building a WebRTC movie talk 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?
Before we stir on, it’s significant that we understand the main implement that we’ll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, movie, 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 effortless to use and understand which makes it a truly fine candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn’t entirely peer-to-peer. The reality is that there’s always a server which bridges the connection inbetween peers. Two or more devices can’t just magically create a connection out of skinny 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 permits 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 embarked 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 indeed work in production. This is because you can only have fifty concurrent connections and the server isn’t in HTTPS. The movie 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 movie or audio call features on your website then you will need the PeerJS server library. However, if you simply need a talk feature you can still use the PeerServer Cloud Service, provided your website doesn’t exceed the concurrent connection limit.
As we budge on through this tutorial I’ll be showcasing you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Movie Talk App
Now it’s time to get our forearms dirty by building the app. Very first we’re going to work with the client-side code and then we’ll budge 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 go after along at home, you will need to have Knot 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:
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event treating.
- 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:
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 duo of inline comments to highlight the significant points.
Take a 2nd 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.
Styling
The app only has minimal styling since most of the prettifying needs are already treated by Picnic. Our extra 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 movie. Let’s take a look at the code.
We commence off by proclaiming a duo 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 :
Next, we create a fresh PeerJS example 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 permits us to set the verbosity of the debug mode ( three being the highest) and the config option permits us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a Overwhelm or TURN server. You don’t truly 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 Overwhelm or TURN server, you can look at this list of loosely available Numb and TURN servers.
When the connection has been successfully initialized on the server, the open event is fired on the peer object. At this point the ID of the current user becomes available and we insert it into the page. This user can then give this ID to another user so that they can connect.
The next line adds a getUserMedia property to the navigator object, the value of which will be the flavor of getUserMedia in the browser. For WebKit browsers such as Chrome or Safari, this will be webkitGetUserMedia . For Firefox, this will be mozGetUserMedia . For other browsers which implement the UserMedia API, this will simply be getUserMedia . Note that this isn’t a fool-proof solution. You can use a shim such as getUserMedia.js if you want a more unified way to use the getUserMedia API.
Then comes a function for getting the current user’s movie feed. This uses the navigator.getUserMedia function which accepts three arguments:
- An object containing configuration options. In this case we set the audio and movie to true so both the camera and microphone in the device will work to provide a movie stream.
- A success callback function which we have specified as the argument for the getVideo function. Note that a stream will be passed as an argument into this anonymous callback function.
- An error callback function which simply alerts the user that an error has occurred.
The onReceiveStream function is responsible for initializing the movie stream;
Once the user clicks Log In, we use PeerJS to connect them with the user with the ID they have specified. The metadata object is used to pass in custom-built data to the peer. In this case we’re passing in the username so that we can display it on the peer’s side. Once the connection is established, the data event is triggered every time a message is sent to the current user. For convenience I’m going to refer to the current user (the one who initiates the connection) as User A, and the peer (the one who is being connected to) as User B.
When User A attempts to connect to User B, the connection event is triggered on User B’s peer object. This permits us to set the connection for User B and get the ID of User A ( connection.peer ). From that connection we can listen for the data event which is triggered whenever User A sends a message to User B. After that, we hide the peer ID text field, update its value to use the ID of the connecting peer and demonstrate the username of User A.
The handleMessage function accepts the data that was sent by the remote peer. This data is used to generate the HTML for the list of messages.
As you might imagine, the sendMessage function is used to send messages to a remote peer.
When a user initiates a call, we use the call method provided by the peer object to call the remote peer. The result of this function call comes back an object in which we can listen for the stream event. This event is fired when the movie feed of the remote peer becomes available to the user who initiated the call.
When the current user makes a call to a remote peer, the call event is triggered. From here we execute the onReceiveCall function to accept the call. If you want to add extra functionality for accepting a call, this is a good place to add it.
The onReceiveCall function accepts the current call object as its argument. The the call object’s response method is invoked to proceed with the call. This accepts the movie feed of the current user as its argument. When the movie feed of the remote peer becomes available, the stream event is triggered. From there we can call the onReceiveStream function to setup the remote peer’s movie.
The Server
Now we’re ready to proceed with the server. Very first, I’ll look at using the PeerServer Cloud Service, after which I’ll examine how to run your own PeerServer using peerjs-server.
Acquiring an API Key from the PeerServer Cloud Service
Go to peerjs.com and click on the Developer – Free button. This will open a modal window that will ask for your credentials. Pack out the form and click on the Accomplish Registration button. Once that’s done, you’ll be redirected to the dashboard page where you can see your API key.
Copy that and update the js/script.js file with your API key. You can liquidate the host , port and path properties from the configuration options in favour of a key property.
And that’s it. You can now hop to the demo section at the end of the article to see what the finished product looks like. Please bear in mind the limitations of this method (namely that you can only have fifty concurrent connections and that movie is not possible).
Running Your Own PeerServer
In this section I’ll walk you through how to run your own peer server.
This will have the following directory structure:
The server component is going to need the peerjs-server. You can install it by creating a package.json file in the root of the server directory and add the following:
Execute npm install to install the dependencies.
As we’re working locally, the server folder can go alongside your public folder in your project’s root directory (just as we have in our GitHub repo). If you’re not working locally, then the server folder will be on a remote server somewhere.
Creating the PeerServer
Inwards your working directory for the server component, create a peer-server.js file and add the following code:
What this does is create a PeerJS server that runs on port nine thousand . You can run the server by executing knot peer-server.js from the terminal. To check if the server is running, access http://localhost:9000/peerjs from the browser and you should see something similar to the following:
Deploying to a Remote Server
If you’re planning to deploy to a remote server later on, it has to be via HTTPS. This is because browsers only permits access to a device’s camera and microphone if the connection is secure. Here’s the code for the PeerServer to make it run on HTTPS:
This requires you to supply the key and certificate file that you acquired from your SSL certificate provider.
Running the App
To run the WebRTC movie talk app, you’ll need to have a server that will serve the files that we’ve created earlier on the client-side section. This is because the getUserMedia API won’t work by simply opening the index.html file on the browser. There are a entire bunch of ways to do this. Here are some of them:
Using PHP
If you have PHP installed on your machine, you can execute the following guideline while inwards the public directory to serve the files.
You can then access the app by going to: http://localhost:3000.
Using Apache
If you have Apache installed, you can copy the peer-messenger directory over to the root of your web folder and access the app using the following URL: http://localhost/public.
Using Knot
If you want to use Knot, you can install Express and have it serve the static files. You can install Express with the following directive:
Next, create an app-server.js file and add the following code:
You can then run the app by executing knot app-server.js . And you can access it by going to: http://localhost:3000.
Whichever method you choose, here’s what the app should look like:
From there the user can come in their username and the ID of the peer they’re attempting to connect to. For convenience let’s call this user the “initiator” because he is the one initiating the connection:
Once the initiator has logged in, peerJS sends the connection data to the peer. For convenience let’s call this user the “receiver”. Once the data is received on the receiver’s side, the screen is updated to showcase the username of the initiator.
The receiver can then come in their username and click on the Login button to begin talking to the initiator:
The initiator replies and clicks on the Call button:
Once the call goes through, the initiator and the receiver both see the movie of the peer they’re connected to:
Conclusion
In this tutorial you’ve learned about PeerJS and how you can use it to create real-time apps. Specifically we’ve created a messaging application that permits the user to send text and make a movie call to a remote peer. PeerJS is a indeed fine cross-browser way to implement WebRTC in web applications.
Don’t leave behind, the code used in this tutorial is available on GitHub. Clone it, make something cool and have joy!
Have you made something cool using PeerJS and/or WebRTC? Let me know in the comments below.
Building a WebRTC Movie Talk Application with PeerJS – SitePoint
Building a WebRTC Movie Talk Application with PeerJS
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 enlargening capacity of browsers to treat peer-to-peer communications in real-time, it’s lighter than ever to build real-time applications. In this tutorial we’ll take a look at PeerJS and how it can make our lives lighter when implementing WebRTC. Via this tutorial we’ll be building a WebRTC movie talk 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?
Before we stir on, it’s significant that we understand the main instrument that we’ll be using. PeerJS is a JavaScript library that simplifies WebRTC peer-to-peer data, movie, 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 effortless to use and understand which makes it a truly superb candidate for implementing cross-browser WebRTC.
PeerServer
WebRTC isn’t fully peer-to-peer. The reality is that there’s always a server which bridges the connection inbetween peers. Two or more devices can’t just magically create a connection out of lean 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 permits 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 commenced 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 truly work in production. This is because you can only have fifty concurrent connections and the server isn’t in HTTPS. The movie 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 movie or audio call features on your website then you will need the PeerJS server library. However, if you simply need a talk feature you can still use the PeerServer Cloud Service, provided your website doesn’t exceed the concurrent connection limit.
As we budge on through this tutorial I’ll be showcasing you how to implement the server with both the PeerServer Cloud Service and the PeerJS server library.
Building the WebRTC Movie Talk App
Now it’s time to get our arms dirty by building the app. Very first we’re going to work with the client-side code and then we’ll budge 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 go after along at home, you will need to have Knot 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:
Dependencies
It also has the following client-side dependencies:
- Picnic — a lightweight CSS framework.
- jQuery — used for selecting elements on the page and event treating.
- 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:
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 duo of inline comments to highlight the significant points.
Take a 2nd 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.
Styling
The app only has minimal styling since most of the prettifying needs are already treated by Picnic. Our extra 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 movie. Let’s take a look at the code.
We commence off by proclaiming a duo 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 :
Next, we create a fresh PeerJS example 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 permits us to set the verbosity of the debug mode ( three being the highest) and the config option permits us to specify the ICE (Interactive Connectivity Establishment) servers. This can either be a Overwhelm or TURN server. You don’t truly 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 Overwhelm or TURN server, you can look at this list of loosely available Numb and TURN servers.
When the connection has been successfully initialized on the server, the open event is fired on the peer object. At this point the ID of the current user becomes available and we insert it into the page. This user can then give this ID to another user so that they can connect.
The next line adds a getUserMedia property to the navigator object, the value of which will be the flavor of getUserMedia in the browser. For WebKit browsers such as Chrome or Safari, this will be webkitGetUserMedia . For Firefox, this will be mozGetUserMedia . For other browsers which implement the UserMedia API, this will simply be getUserMedia . Note that this isn’t a fool-proof solution. You can use a shim such as getUserMedia.js if you want a more unified way to use the getUserMedia API.
Then comes a function for getting the current user’s movie feed. This uses the navigator.getUserMedia function which accepts three arguments:
- An object containing configuration options. In this case we set the audio and movie to true so both the camera and microphone in the device will work to provide a movie stream.
- A success callback function which we have specified as the argument for the getVideo function. Note that a stream will be passed as an argument into this anonymous callback function.
- An error callback function which simply alerts the user that an error has occurred.
The onReceiveStream function is responsible for initializing the movie stream;
Once the user clicks Log In, we use PeerJS to connect them with the user with the ID they have specified. The metadata object is used to pass in custom-made data to the peer. In this case we’re passing in the username so that we can display it on the peer’s side. Once the connection is established, the data event is triggered every time a message is sent to the current user. For convenience I’m going to refer to the current user (the one who initiates the connection) as User A, and the peer (the one who is being connected to) as User B.
When User A attempts to connect to User B, the connection event is triggered on User B’s peer object. This permits us to set the connection for User B and get the ID of User A ( connection.peer ). From that connection we can listen for the data event which is triggered whenever User A sends a message to User B. After that, we hide the peer ID text field, update its value to use the ID of the connecting peer and demonstrate the username of User A.
The handleMessage function accepts the data that was sent by the remote peer. This data is used to generate the HTML for the list of messages.
As you might imagine, the sendMessage function is used to send messages to a remote peer.
When a user initiates a call, we use the call method provided by the peer object to call the remote peer. The result of this function call comebacks an object in which we can listen for the stream event. This event is fired when the movie feed of the remote peer becomes available to the user who initiated the call.
When the current user makes a call to a remote peer, the call event is triggered. From here we execute the onReceiveCall function to accept the call. If you want to add extra functionality for accepting a call, this is a good place to add it.
The onReceiveCall function accepts the current call object as its argument. The the call object’s reaction method is invoked to proceed with the call. This accepts the movie feed of the current user as its argument. When the movie feed of the remote peer becomes available, the stream event is triggered. From there we can call the onReceiveStream function to setup the remote peer’s movie.
The Server
Now we’re ready to proceed with the server. Very first, I’ll look at using the PeerServer Cloud Service, after which I’ll examine how to run your own PeerServer using peerjs-server.
Acquiring an API Key from the PeerServer Cloud Service
Go to peerjs.com and click on the Developer – Free button. This will open a modal window that will ask for your credentials. Pack out the form and click on the Finish Registration button. Once that’s done, you’ll be redirected to the dashboard page where you can see your API key.
Copy that and update the js/script.js file with your API key. You can eliminate the host , port and path properties from the configuration options in favour of a key property.
And that’s it. You can now hop to the demo section at the end of the article to see what the finished product looks like. Please bear in mind the limitations of this method (namely that you can only have fifty concurrent connections and that movie is not possible).
Running Your Own PeerServer
In this section I’ll walk you through how to run your own peer server.
This will have the following directory structure:
The server component is going to need the peerjs-server. You can install it by creating a package.json file in the root of the server directory and add the following:
Execute npm install to install the dependencies.
As we’re working locally, the server folder can go alongside your public folder in your project’s root directory (just as we have in our GitHub repo). If you’re not working locally, then the server folder will be on a remote server somewhere.
Creating the PeerServer
Inwards your working directory for the server component, create a peer-server.js file and add the following code:
What this does is create a PeerJS server that runs on port nine thousand . You can run the server by executing knot peer-server.js from the terminal. To check if the server is running, access http://localhost:9000/peerjs from the browser and you should see something similar to the following:
Deploying to a Remote Server
If you’re planning to deploy to a remote server later on, it has to be via HTTPS. This is because browsers only permits access to a device’s camera and microphone if the connection is secure. Here’s the code for the PeerServer to make it run on HTTPS:
This requires you to supply the key and certificate file that you acquired from your SSL certificate provider.
Running the App
To run the WebRTC movie talk app, you’ll need to have a server that will serve the files that we’ve created earlier on the client-side section. This is because the getUserMedia API won’t work by simply opening the index.html file on the browser. There are a entire bunch of ways to do this. Here are some of them:
Using PHP
If you have PHP installed on your machine, you can execute the following guideline while inwards the public directory to serve the files.
You can then access the app by going to: http://localhost:3000.
Using Apache
If you have Apache installed, you can copy the peer-messenger directory over to the root of your web folder and access the app using the following URL: http://localhost/public.
Using Knot
If you want to use Knot, you can install Express and have it serve the static files. You can install Express with the following instruction:
Next, create an app-server.js file and add the following code:
You can then run the app by executing knot app-server.js . And you can access it by going to: http://localhost:3000.
Whichever method you choose, here’s what the app should look like:
From there the user can come in their username and the ID of the peer they’re attempting to connect to. For convenience let’s call this user the “initiator” because he is the one initiating the connection:
Once the initiator has logged in, peerJS sends the connection data to the peer. For convenience let’s call this user the “receiver”. Once the data is received on the receiver’s side, the screen is updated to display the username of the initiator.
The receiver can then come in their username and click on the Login button to begin talking to the initiator:
The initiator replies and clicks on the Call button:
Once the call goes through, the initiator and the receiver both see the movie of the peer they’re connected to:
Conclusion
In this tutorial you’ve learned about PeerJS and how you can use it to create real-time apps. Specifically we’ve created a messaging application that permits the user to send text and make a movie call to a remote peer. PeerJS is a truly good cross-browser way to implement WebRTC in web applications.
Don’t leave behind, the code used in this tutorial is available on GitHub. Clone it, make something cool and have joy!
Have you made something cool using PeerJS and/or WebRTC? Let me know in the comments below.
Leave a Reply