首页 > 解决方案 > PeerJS - connection.on('open')未执行

问题描述

  1. 当对等体 1 连接到对等体 2 时

    1. 图片中突出显示的代码应该触发
    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!');
});

标签: javascriptnode.jswebrtcp2ppeerjs

解决方案


你必须为你设置一个服务器端 PeerJS

运行免费的云托管版本的 PeerServer 进行测试,只需更改

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

var MyPeerId ;
const peer = new Peer();

并获得一个 id 使用:

  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
 }

推荐阅读