PeerJS: Other Peer Detected but Connection Not Open

3.4k views Asked by At

I am using PeerJS to establish peer-to-peer connections. It seems that I have been able to establish a connection momentarily but I have been unable to send and receive data over the connection. Below is my code:

var peer;
var nbcc = [];

function updatePeerConnections(){
    if (!id) return;
    if (!peer) {
        peer = new Peer(id,{key: '52hhtusf1t0rudi'});
        peer.on('open', function(conn) {
            console.log('new connection');
        });
        peer.on('connection', function(conn) {
            conn.on('open', function(){
                console.log('connected!');
                conn.on('data', function(data){
                    let o = JSON.parse(data);
                    console.log('updating car ' + o.i);
                    updateCarMarker(o.id,o.lat,o.lng);
                 });

            });            
            conn.on('error', function(err){
               console.log(err);
            });
            console.log(conn.open+': remote peer detected: '+conn.peer);
            conn.id = conn.peer;
            nbcc[conn.peer] = conn;
        });
        peer.on('error', function(err){
            console.log(err.type);
        });
        updateConnections();        
    } else {
       updateConnections();
    }
}

function updateConnections(){
    for (cm of Object.values(carMarkers)){
        if (cm.id!=id && !Object.keys(nbcc).includes(cm.id)){
            console.log('connecting to '+cm.id)
            nbcc[cm.id] = peer.connect(cm.id);
            nbcc[cm.id].id = cm.id;
            nbcc[cm.id].on('error', function(err){
                console.log(err);
            });
            nbcc[cm.id].on('open', function(){
                console.log('connected!');
                nbcc[cm.id].on('data', function(data){
                    let o = JSON.parse(data);
                    console.log('updating car ' + o.i);
                    updateCarMarker(o.id,o.lat,o.lng);
                 });
            });
        }
    }
}

On the browser console, it printed 'new connection' and then 'false: remote peer detected: 879874543958', where the id is the remote peer (another tab in the browser). It never printed 'connected!' nor any error message. What is wrong with the code?

2

There are 2 answers

1
Chong Lip Phang On BEST ANSWER

I found the problem!

It is with this line:

   peer = new Peer(id,{key: '52hhtusf1t0rudi'});

We must not set the optional parameter 'id' ourselves. Instead, we should receive it in peer.on('connection',function(id){...})

Duh. Why allow that parameter to be set when it musn't be set. That is confusing.

1
Pradipto SenSarma On

If this works in localhost but doesn't work over the internet then you are probably missing a STUN and a TURN server.

By default peer js uses the google global stun server but you will have to get a turn server for this to work in production.