Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peerjs not working.. no errors

I am trying to do very simple one page test of peerjs as i learn it.

However, the code below doesn't seem to work. I have gone over documents three times. But can't find any error in my code and there are no error in output either.

For my inspiration i used this: http://cdn.peerjs.com/demo/helloworld.html

My code

var p1 = new Peer('a351TxFJLKnljhl22',{key: 'key'});
var p2 = new Peer('a351TxFJLKnljhl22',{key: 'key'});

p1.on('open', function(id) {

    console.log('connected to server');
    var c = p1.connect('a351TxFJLKnljhl22');
        c.on('open', function(data) {    
            console.log('connected to peer');
            c.send('connection working');
        });    
});

p2.on('connection', function(connection) {
      connection.on('data', function(data) {
          console.log('p2 speaking..got from p1: '+data);
      });
});

I expect to get connection working in console.

like image 664
Muhammad Umer Avatar asked Nov 25 '25 16:11

Muhammad Umer


1 Answers

According to the API:

var peer = new Peer([id], [options]);

You will need two different id's, like this:

var p1 = new Peer('a351TxFJLKnljhl22',{key: 'key'});
var p2 = new Peer('asdf345wef234fgwe',{key: 'key'});

Your P1 code looks right to me. Your P2 code needs to check for 'open' after connection, as you may wish to send data back the other way at some stage.

p2.on('connection', function(connection) {
      connection.on('open', function(data) {
          console.log('p2 open');
          connection.on('data', function(data) {
               console.log('p2 speaking..got from p1: '+data);
               // may wish to use connection.send() here
          });
      }); 
});

For a slightly different way to do the same thing using only 1 connection, check this tutorial: http://blog.parkbenchgames.com/2014/12/16/how-to-use-peerjs/

like image 99
ChrisAdmin Avatar answered Nov 27 '25 06:11

ChrisAdmin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!