PeerJS - connection.on('open') not executing

Viewed 977
  1. When peer 1 connects to peer 2

    1. the highlighted code in the picture should fire
    2. peer 2 should send peer 1 "hello!"
    3. peer 1 should have "hello!" printed in its console
  2. Peer 1 connects to peer 2

  3. Problem: peer 1 does not have "hello!" printed in its console

enter image description here

// make a new peer
const peer = new Peer('', {
  host: '/',
  port: '3001'
});


// "connection" event fires when someone tries to connect to us
peer.on('connection', (conn) => {  
  console.log('someone connected');
  
  // "data" event fires when someone sends us a message
  conn.on('data', (data) => {
    console.log(data);
  });
  
  // ===========================================================================
  
  // Problem: Both Attempt 1 and Attempt 2 fail to run
  
  // ATTEMPT 1: "open" event fires when the connection is opened
  conn.on('open', () => {
    conn.send('hello!');
  });
  
  // ATTEMPT 2:
  conn.send('hello!');
  // ===========================================================================
});


// connect to a peer
const conn = peer.connect('another-peers-id');


// after connecting to peer, send "hi" to them
conn.on('open', () => {
  conn.send('hi!');
});
2 Answers

you have to set a server side for you PeerJS

run a free cloud-hosted version of PeerServer for testing , just change the

const peer = new Peer('', {
  host: '/',
  port: '3001'
});

to

var MyPeerId ;
const peer = new Peer();

and to get an id use :

  peer.on('open',  function(){
  MyPeerId = peer.id;
});
//this is an async function so you have be sure that you got an id before connection to someone else

//rest of your code here

function Connect(OtherPeerId){
 if(!MyPeerId)
 return 0; // you didn't get a peerid yet
 //rest of your code
 }

Actually, there might be a problem with the connection itself.

After you do this

const peer = new Peer('', {
  host: '/',
  port: '3001'
});

a new peer object is created and retured but, socket takes a bit of time to open up. You can check this if you set the debug to 3,

console

If connect function is called before getting socket open, connect will fail

const conn = peer.connect('another-peers-id');

You can try add a setTimeout for connect to test this theory.

setTimeout(() => {
     const conn = peer.connect('id');
}, 1000);

And same problem exists with 'connection' callback also You can add setTimeout inside connection callback too

peer.on("connection", (conn) => {
    console.log("Connected to: " + conn.peer);
    setTimeout(() => {
       ...enter code here...
    }
)
Related