2014-10-11 61 views
0

我試圖做非常簡單的peerjs的一個頁面測試,因爲我知道它。Peerjs不工作..沒有錯誤

但是,下面的代碼似乎不起作用。我已經翻了三遍文件。但是在我的代碼中找不到任何錯誤,輸出也沒有錯誤。

對於我的靈感,我用這樣的:http://cdn.peerjs.com/demo/helloworld.html

我的代碼

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); 
     }); 
}); 

我希望得到連接控制檯工作。

回答

0

根據API:

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

您將需要兩個不同的ID的,就像這樣:

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

你P1的代碼看起來我的權利。 您的P2代碼在連接後需要檢查'open',因爲您可能希望在某個階段以另一種方式發送數據。

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 
      }); 
     }); 
}); 

對於一個稍微不同的方式只用1連接做同樣的事情,看看這個教程:http://blog.parkbenchgames.com/2014/12/16/how-to-use-peerjs/