Reputation: 991
Is there a way with peerjs to tell if a connection has been successfully made when using peer.connect()
. Reading the docs the only events emitted for a DataConnection
are data
, open
, close
and error
. And error
doesn't emit if there was no connection made.
I am trying to create a peer to peer file transfer by sending chunks of data. My current flow is to first connect to the user and save that connection for future use. Then I would like to send them a message that a transfer has been initialized so they can either accept or deny the transfer.
My big problem is there is no error
emitted when a connection cannot be established. You can attach an error handler to the peer itself but it just emit a generic error something like cannot connect to peer {peerid}
. This isn't really useful because I would have to unreliably parse this string to get the connection id. So there is really no way of knowing whether peer.connect({peerid})
was actually connected or not.
So if I were to write a function to connect to a peer then there is really now way of knowing if the connection is successful. So something like so:
async function connect(to) {
return new Promise((resolve, reject) => {
const conn = peer.connect(to)
// This doesn't exist
conn.on('success', () => {
connections.set(to, conn)
resolve(conn)
})
// This exists but doesn't emit on unsuccessful connection
conn.on('error', (err) => reject(err))
})
}
Then if I can store the connection I can just grab the connection and send with it.
function send(to, data){
const conn = connections.get(to)
if(!conn) throw new Error('No connection available')
conn.send(data)
}
So currently I have resorted to using the listAllPeers()
function to get a list of connected peers. Then running that in a setInterval
until the peer has been found. This seems like a bit more work than needs to be done and also requires and extra call to the peer server for no reason other than to check if a peer is available before connecting which seems stupid. I could also probably set up a mechanism to just try send messages at an interval and wait for a response. This all seems like a poor solution.
So is there a good way to tell if a connection has been established or am I stuck with my current solution?
Upvotes: 1
Views: 650
Reputation: 9
Just use conn.on("open");
const conn = peer.connect(to)
// This exists
conn.on('open', () => {
connections.set(to, conn)
resolve(conn)
})
// This exists but doesn't emit on unsuccessful connection
conn.on('error', (err) => reject(err))
Upvotes: -1