/

Introduction to PeerJS: A Simplified WebRTC Library

Introduction to PeerJS: A Simplified WebRTC Library

When it comes to working with WebRTC, the process can be challenging. However, with the help of PeerJS, a powerful library, WebRTC becomes much easier to handle.

In a previous blog post about WebRTC, I discussed the intricate details of using the protocol to establish direct communication between two web browsers.

During the tutorial, I mentioned that there are libraries available that simplify the complexities involved in enabling WebRTC communication. One such library is PeerJS, which offers a straightforward approach to real-time communication.

To begin, you’ll need a backend to facilitate the synchronization between two clients before they can communicate directly.

Follow these steps to set up PeerJS:

  1. Initialize an npm project in a folder using the command npm init.
  2. Install PeerJS by running npm install peerjs.
  3. Start the PeerJS server using npx with the command npx peerjs --port 9000. You can explore additional options by running npx peerjs --help.

Congratulations! Your backend is now ready for use.

Let’s create a simple application where there is one receiver and one sender.

To start, we need to create the receiver, which connects to our PeerJS server and listens for incoming data. The first parameter in new Peer() is the peer name, which we’ll set as receiver for clarity.

Include the PeerJS client by adding the following script tag to your HTML file (change the library version to the latest available):

1
<script src="https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js"></script>

Next, initialize the Peer object. The connection event is triggered when another peer connects to us. When data is received, the data event is triggered, allowing us to process the payload.

1
2
3
4
5
6
7
const peer = new Peer('receiver', { host: 'localhost', port: 9000, path: '/' });

peer.on('connection', (conn) => {
conn.on('data', (data) => {
console.log(data);
});
});

Now, let’s create the other end of the communication, known as the sender. This peer will connect to the receiver peer we registered earlier. Once the connection is established, the open event is triggered, enabling us to use the send() method to send data to the receiver.

1
2
3
4
5
6
7
const peer = new Peer('sender', { host: 'localhost', port: 9000, path: '/' });

const conn = peer.connect('receiver');

conn.on('open', () => {
conn.send('hi!');
});

This is the most basic example you can create using PeerJS.

To test the functionality, open the receiver page first, followed by the sender page. The receiver will receive the message directly from the sender, without any involvement from a centralized resource. The server is only necessary to exchange initial information between the two peers, after which it no longer interferes.

tags: [“WebRTC”, “PeerJS”, “real-time communication”, “backend”, “receiver”, “sender”]