PeerJS - connection.on('open') не выполняется

  1. Когда узел 1 подключается к узлу 2

    1. the highlighted code in the picture should fire
    2. узел 2 должен отправить узлу 1 привет!
    3. коллега 1 должен приветствовать! напечатано в его консоли
  2. Пир 1 подключается к пиру 2

  3. Проблема: у узла 1 нет приветствия! печатается в консоли

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

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

person alphabet    schedule 11.01.2021    source источник


Ответы (1)


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

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

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

to

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
 }
person Community    schedule 11.01.2021
comment
У меня есть одноранговый сервер, работающий на порту 3001. С этой частью все в порядке. - person alphabet; 11.01.2021