javascript - PeerJS - connection.on ('open' )未执行

标签 javascript node.js webrtc p2p peerjs

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

    1. 图片中突出显示的代码应该触发
    2. 对等点 2 应向对等点 1 发送“你好!”
    3. 对等点 1 应该有“hello!”在其控制台中打印
  2. 对等点 1 连接到对等点 2

  3. 问题: 对等点 1 没有“hello!”在其控制台中打印

enter image description here

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

最佳答案

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

完成此操作后

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

创建并返回一个新的对等对象,但是套接字需要一些时间才能打开。 如果将调试设置为 3,则可以检查此项,

console

如果在打开套接字之前调用 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...
    }
)

关于javascript - PeerJS - connection.on ('open' )未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65673692/

相关文章:

javascript - 无法对 URL 进行网页截图

javascript - 如何瞄准正确的 child ?

node.js - 函数中的函数返回值

node.js - 使用 Node js 一步步创建 webrtc 视频、语音通话和文件传输 Q-A

java - 在 tomcat 7.0.47 websocket 上出现 404 错误

webrtc - 在 TURN 配置中无法访问 NAT 后面的 Coturn

javascript - NodeJS 异步函数不起作用

javascript - 有没有办法使用 'unload\navigator.sendBeacon' + 'GraphQL' 将数据发送到服务器?

node.js - 逐行读取 .json 文件

node.js - 当使用带有 useUnifiedTopology 选项的 Mongoose.connect 时,返回的 Promise 不会捕获错误