Welcome to a tutorial on WebRTC with Javascript and NodeJS. Need to do a peer-to-peer connection with Javascript? Yes, that is possible. Allow me to simplify things and save you some time:
One of the easier ways to handle WebRTC (peer-to-peer) is to use the PeerJS and PeerServer libraries.
- Create a PeerServer in NodeJS to handle the handshaking.
- In the webpages (JS), “register” the clients with the PeerServer first, then connect to each other.
Sounds easy enough? Read on for the example!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
WEBRTC PEER-TO-PEER
All right, let us now get into the simple example of peer-to-peer in Javascript and NodeJS.
QUICK SETUP
Run npm i express peer
to install the required modules.
STEP 1) EXPRESS & PEER SERVER
// (A) REQUIRED MODULES
// npm install express peer
const express = require("express"),
path = require("path"),
{ PeerServer } = require("peer");
// (B) EXPRESS SERVER
// http://localhost/a
// http://localhost/b
const app = express();
app.get("/a", (req, res) => res.sendFile(path.join(__dirname, "2-peer-a.html")));
app.get("/b", (req, res) => res.sendFile(path.join(__dirname, "3-peer-b.html")));
app.listen(80);
// (C) PEER SERVER
// http://localhost:9000/myapp
const peerServer = PeerServer({
port: 9000,
path: "/myapp"
});
First, run npm install express peer
in your project folder, then launch the above script node 1-server.js
. This will deploy:
http://localhost/a
The “first user”.http://localhost/b
The “second user”.http://localhost:9000/myapp
The peer server.
STEP 2) PEER A
<!-- (A) LOAD PEERJS -->
<script src="https://unpkg.com/peerjs@1.4.17/dist/peerjs.min.js"></script>
<!-- (B) PEER-TO-PEER -->
<script>
// (B1) HANDSHAKE WITH PEER SERVER
const peer = new Peer("PEER-A", {
host: "localhost",
port: 9000,
path: "/myapp"
});
// (B2) READY
peer.on("open", id => console.log("Your ID is " + id));
// (B3) ON RECEIVING MESSAGE FROM OTHER PEERS
peer.on("connection", conn => {
conn.on("data", data => console.log(data));
// conn.close();
});
</script>
- (B1) As in the introduction, we have to “register” with the peer server first. The PeerJS library has simplified a lot of things, just create a
new Peer(USER ID, OPTIONS)
object. Take note of theUSER ID
here, we will go through more below. - (B2) On successful”registration” with the peer server, this is a good time to enable your HTML controls and processes. You can also use
peer.on("close") peer.on("error")
to further manage your processes. - (B3) When a peer connects and sends data over – We simply output it into the console in this example.
Go ahead – Open this in your browser http://localhost/a
and open the developer’s console.
STEP 3) PEER B
<!-- (A) LOAD PEERJS -->
<script src="https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js"></script>
<!-- (B) PEER-TO-PEER -->
<script>
// (B1) HANDSHAKE WITH PEER SERVER
const peer = new Peer("PEERB", {
host: "localhost",
port: 9000,
path: "/myapp"
});
// (B2) READY - CONNECT & SEND MESSAGE TO PEER A
peer.on("open", id => {
console.log("Your ID is " + id);
var conn = peer.connect("PEER-A");
conn.on("open", () => conn.send("Hi from PEER-B!"));
});
</script>
- (B1) This is the same
new Peer()
. Take note of the user ID again, every user should be assigned a unique ID. - (B2) Connect to peer A, send “Hi from PEER-B”.
Yep, go ahead and open http://localhost/b
in another browser (or window). Watch how Hi from PEER-B!
pops up in the developer’s console of Peer A. Reminder, this is a direct peer-to-peer send. That is, the message is not passed through the peer server.
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
EXTRA) PEER OR USER-ID
That covers the super simple example, but there should be a burning question – Do we have to manually assign a unique user ID all the time? How does that even work!? It is difficult to answer this question, as everyone is building apps in different ways. Let me give a few examples:
- If you have an existing user database, it will make sense to use the user ID in the session or database. For example, in PHP –
new Peer("<?=$_SESSION["USER-ID"]?>", ...)
. - Some of you may want to build a “private room” of sorts. In this case:
- It is better to generate a unique ID for the room first, for example,
ROOM-ABC
. - Add a password to join the room.
- Then, assign the ID only when the user enters the room with the correct password –
ROOM-ABC-USER-1
. - Users can then broadcast within the room, or choose to private chat with other people in the room.
- It is better to generate a unique ID for the room first, for example,
- Lastly,
new Peer(null, OPTIONS)
will automatically generate a unique ID. Maybe generate a URL for the user to share –http://site.com/chatwith/?user=ID
.
As you can see, there are endless ways to handle the user ID. I cannot give a “fixed example”, you will have to decide for yourself.
EXTRA) HOW ABOUT VIDEO STREAMS?
navigator.getUserMedia({video: true, audio: true})
.then(stream => {
var call = peer.call("PEER-ID", stream);
call.on("stream", pstream => document.getElementById("VIDEO").srcObject = pstream);
})
.catch(err => console.error(err));
peer.on("call", call => {
navigator.getUserMedia({video: true, audio: true})
.then(stream => {
call.answer(stream); // answer the call with an A/V stream.
call.on("stream", pstream) => document.getElementById("VIDEO").srcObject = pstream);
})
.catch(err => console.error(err));
});
Yep, these are just about ripped from the PeerJS documentation itself.
CONNECTING TO MULTIPLE PEERS
Of course, you can make multiple peer-to-peer connections. But take note that it is ultimately PEER-TO-PEER, if you are still lost, that is one-to-one. If you want to do one-to-many or many-to-many, that is called “broadcast”. Look into web sockets instead, link below.
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- WebRTC – CanIUse
Surprisingly well supported in most modern browsers.
LINKS & REFERENCES
- NodeJS Live Chat With WebSocket – Code Boxx
- PeerJS and PeerServer
- WebRTC API – MDN
- WebSocket API – MDN
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!