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?
I found the problem!
It is with this line:
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.