'How to set up a basic Peerjs connection?

I am quite new to Javascript so please bear in mind I may be quite slow to understand things. I have spent several hours trying to get a very simple peerjs connection where there are two users who run a html file in the browser, connect and then send hello to eachother. I've tried everything I can think of and have looked at all the documentation but can't seem to even get a connection to work. This is what I have so far (largely taken from this page https://peerjs.com/docs.html):

For User1:

<html>
    <body>
        <script src="https://unpkg.com/[email protected]/dist/peerjs.min.js"></script>
        <script src="test1.js"></script>
    </body>
</html>

__test1.js__
var peer = new Peer("User1");
peer.on('open', function(id) {
  console.log('My peer ID is: ' + id);
});
var conn = peer.connect('User2');

For User2:

<html>
    <body>
        <script src="https://unpkg.com/[email protected]/dist/peerjs.min.js"></script>
        <script src="test2.js"></script>
    </body>
</html>

__test2.js__
var peer = new Peer("User2");
peer.on('open', function(id) {
  console.log('My peer ID is: ' + id);
});
peer.on('connection', function(conn) { console.log("Connected") });

When I run the second HTML file followed by the first, I correctly get their ID's outputted but the connection never happens. What am I doing wrong? Thank you.



Solution 1:[1]

You need to connect to a peer after connection to the server is established.

This means you need to invoke connect after the open callback:

var peer = new Peer("User1");
peer.on('open', function(id) {
  console.log('My peer ID is: ' + id);
  var conn = peer.connect('User2');
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1