Very Simple WebRTC Example With Javascript NodeJS (Peer-To-Peer)

Welcome to a tutorial and very simple example of WebRTC with Javascript and NodeJS. A peer-to-peer connection with Javascript? That is very interesting. But after hours of reading the documentation on the Internet, it has been nothing but a painful experience. So, 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, to handle the handshaking.
  • Get the clients to “register” with the PeerServer first, then connect to each other.

Sounds easy enough? Read on for the example!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Peer-To-Peer Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • You will need your own HTTP server (XAMPP, Apache, IIS, NGINX, or create one using Node itself).
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

WEBRTC PEER-TO-PEER

All right, let us now get into the simple example of peer-to-peer in Javascript and NodeJS.

 

STEP 1) PEER SERVER

1-server.js
const { PeerServer } = require("peer");
const peerServer = PeerServer({
  port: 9000,
  path: "/myapp"
});

First, run npm install peer in your project folder, then launch the above script node 1-server.js. This will deploy the peer server at http://localhost:9000/myapp.

 

STEP 2) PEER A

2-peer-a.html
<!-- (A) LOAD PEERJS -->
<script src="https://unpkg.com/peerjs@1.3.1/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 the USER 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/2-peer-a.html and open the developer’s console.

 

 

STEP 3) PEER B

3-peer-b.html
<!-- (A) LOAD PEERJS -->
<script src="https://unpkg.com/peerjs@1.3.1/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 this 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.

 

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.
  • 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?

CALL ANOTHER PEER
navigator.getUserMedia({video: true, audio: true})
.then((mystream) => {
  var call = peer.call("PEER-ID", mystream);
  call.on("stream", (peerstream) => {
    document.getElementById("VIDEO").srcObject = peerstream;
  });
})
.catch((err) => { console.log(err); });
ANSWER CALL
peer.on("call", (call) => {
  navigator.getUserMedia({video: true, audio: true})
  .then(mystream => {
    call.answer(stream); // Answer the call with an A/V stream.
    call.on("stream", (peerstream) => {
      document.getElementById("VIDEO").srcObject = peerstream;
    });
  })
  .catch((err) => { console.log(err); });
});

Yep, these are just about ripped from the PeerJS documentation itself.

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

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

Surprisingly well supported in most modern browsers.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

WebRTC With Javascript NodeJS (Click To Enlarge)

 

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!

Leave a Comment

Your email address will not be published. Required fields are marked *