PeerJS-Connection.on(‘Open’)未执行

kokeuurv  于 2022-09-18  发布在  Java
关注(0)|答案(2)|浏览(242)

1.当对等方%1连接到对等方%2时

1.图片中突出显示的代码应该会触发
1.对等点2应该向对等点1发送“你好!”
1.对等体1应该有“Hello!”在其控制台中打印
1.对等方%1连接到对等方%2
1.*问题:对等体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!');
});
pkwftd7m

pkwftd7m1#

您必须为您的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
 }
7cjasjjr

7cjasjjr2#

实际上,连接本身可能存在问题。

在你完成这项工作之后

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

创建并重新创建了一个新的对等对象,但打开套接字需要一些时间。如果将调试设置为3,则可以检查这一点。

如果在打开套接字之前调用CONNECT函数,则connect将失败

const conn = peer.connect('another-peers-id');

您可以尝试为connect添加一个setTimeout来测试这个理论。

setTimeout(() => {
     const conn = peer.connect('id');
}, 1000);

'connection'回调也存在同样的问题,您也可以在连接回调中添加setTimeout

peer.on("connection", (conn) => {
    console.log("Connected to: " + conn.peer);
    setTimeout(() => {
       ...enter code here...
    }
)

相关问题