PeerJS — connection.on(‘открыть’) не выполняется

#javascript #node.js #webrtc #p2p #peerjs

#javascript #node.js #webrtc #p2p #peerjs ( пирджс )

Вопрос:

  1. Когда одноранговый узел 1 подключается к одноранговому узлу 2
    1. выделенный код на картинке должен сработать
    2. одноранговый узел 2 должен отправить одноранговому узлу 1 «привет!»
    3. узел 1 должен иметь «привет!», напечатанный в его консоли
  2. Узел 1 подключается к узлу 2
  3. Проблема: у узла 1 нет «hello!», напечатанного в его консоли

введите описание изображения здесь

 // 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!');
});
 

Ответ №1:

вы должны установить серверную часть для PeerJS

запустите бесплатную облачную версию PeerServer для тестирования, просто измените

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

Для

 var MyPeerId ;
const peer = new Peer();
 

и чтобы получить удостоверение личности, используйте :

   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
 }
 

Комментарии:

1. У меня есть одноранговый сервер, работающий на порту 3001. Эта часть в порядке.