如何使用 peerjs 连接到主机?

How to connect to a host with peerjs?

我正在尝试使用 peerjs to connect an host with a client. I have two files (one for the host, one for the client). The host will generate a peerId which the client is using to connect to him. It's basically the tutorial from here

host.html

const peer = new Peer()

peer.on('open', () => {
  console.log('ID: ' + peer.id)
})

peer.on('connection', (conn) => {
  conn.on('data', (data) => {
    // Will print 'hi!'
    console.log(data)
  })
  conn.on('open', () => {
    conn.send('hello!')
  })
})
<script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js"></script>

client.html

const peer = new Peer()

const conn = peer.connect('1781a113-d095-4be5-9969-b80d9c364f6b')
conn.on('open', () => {
  conn.send('hi!')
})
<script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js"></script>

客户端既没有连接也没有发送消息。我尝试使用他们的示例连接到我的主机,这很有效。我能够向主机发送消息。我的客户有什么问题?

文档中有点含糊,but if you don't wait on the open event, messages to the server will be queued。我不确定是否需要额外的配置来启用排队,但在你的情况下只需等待打开事件就可以了

const peer = new Peer()

peer.on('open', () => {
    const conn = peer.connect('1781a113-d095-4be5-9969-b80d9c364f6b')
    conn.on('open', () => {
        conn.send('hi!')
    })
})

请记住,在您的 'host' 中生成的对等 ID 会在您每次刷新浏览器时发生变化,因此您可能希望选择自己的 ID 而不是随机获取一个