6

I'm trying to use 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>

The client is not connecting nor sending messages. I tried to use their example to connect to my host and this was working. I was able to send messages to the host. What is the issue with my client?

Lars Flieger
  • 2,421
  • 1
  • 12
  • 34

1 Answers1

3

It's a little vague in the documentation, but if you don't wait on the open event, messages to the server will be queued. I'm not sure if there is additional configuration needed to enable queuing, but simply waiting on the open event should work in your case

const peer = new Peer()

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

Keep in mind that the peer id generated in your 'host' will change every time you refresh the browser, so you might want to pick your own id instead of getting a random one

Sully
  • 395
  • 3
  • 7
  • Thank you very much! This solved my issue. (I didn't get that from the docs) Thank you! – Lars Flieger Jun 08 '21 at 20:15
  • I searched for hours for an answer and was about to discard my project when I saw your answer. And it worked!!! Thanks a million! – coderGtm Jul 13 '22 at 08:31