Search code examples
javascriptwebrtcp2ppeerjspeer

How to connect to a host with peerjs?


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/[email protected]/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/[email protected]/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?


Solution

  • 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