Regular Memory

Simple Peer2Peer Connections with PeerJS

Posted at — Nov 28, 2019

Overview

Writing apps and tools for the web is fun, but the next step is allowing users to contact each other whether to share content, cooperate with, or compete against each other. Connecting people together often requires one to write a public server to which all parties connect in order to share messages. Even Peer2Peer connections (directly from one computer to another) require a server to establish the connection prior to two parties communicating directly. In this article, we see the PeerJS is a convient way to set-up a P2P connection and PeerJS hosts a free public server, so we can focus on writing client-side Javascript.

PeerJS: PeerJS wraps the browser’s WebRTC implementation to provide a complete, configurable, and easy-to-use peer-to-peer connection API. Equipped with nothing but an ID, a peer can create a P2P data or media stream connection to a remote peer.

The Code

The code is pretty straight forward, and I’ve added comments to explain what each line does. Copy the code below into an index.html file or download the code here.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE html>
<html><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Include the P2P library -->
    <script src="https://unpkg.com/peerjs@1.0.0/dist/peerjs.min.js"></script>

    <style>
    html, body {
        padding: 30px;
        margin: 0px;
        font-size: 1.2em;
    }
    </style>
</head>
<body>
    <h1>P2P Connection Establishment Example</h1>
    <p>Open the web inspector, and click the Console tab to see results.</p>

    <!-- Use PeerJS API -->
    <script>

        // Create a Peer
        var peer = new Peer();

        // Print PeerID to the Console
        let peer_id;
        peer.on('open', function(id) {
            peer_id = id;
            console.log('Your peer ID: ' + id);
        });

        // Listen for an incoming connection
        peer.on('connection', function(conn) {
            conn.on('data', function(data) {

                // Log received data
                console.log(data);
            });
        });

        // Connect to a peer
        var conn;
        function connect(peerID) {
            conn = peer.connect(peerID);

            // 'open' is called on successful connection to PeerServer
            conn.on('open', function() {

                // Send a hello message to a peer            
                conn.send(peer_id + " has connected with you");

                // Inform client of connection
                console.log("You have connected with: " + peerID);
            });
        }

        // Send a message to a Peer you have connected with
        function send(msg) {
            if (conn != undefined)
                conn.send(msg);
        }
    </script>
</body>
</html>

In summary, the code above will print your PeerID to the console. One can then call connect(PeerID), where PeerID is someone else’s PeerID, to connect with a peer. Once the connection is established, call msg(msg_text) to send a message to a peer, where msg_text is a string representing the message you want to send.

Connecting with a Peer

Here I show screenshots where I have opened the console in the web inspector for two different tabs on the same machine. Note, this will also work between any two machines that are able to establish a P2P connection, which might exclude cell phones, some older browsers, and machines behind firewalls, but a P2P connection will work in a lot of cases!

P2P in Action

If you want to see P2P in-action checkout an interactive Go board I built. Players can connect with P2P to sync board and menu state between clients.

comments powered by Disqus