Last active
August 3, 2019 19:29
-
-
Save afrokick/06f30a550008132c4aa5cf3fe987238d to your computer and use it in GitHub Desktop.
Example of PeerJS DataConnection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global Peer */ | |
document.addEventListener('DOMContentLoaded', () => { | |
initiator(); | |
another(); | |
}, false); | |
// initiator side | |
const initiator = () => { | |
const peer = new Peer('initiatorId', { debug: 3 }); | |
peer.on('open', (id) => { | |
const conn = peer.connect('calleId'); | |
conn.on('error', (error) => { | |
console.error(error); | |
}); | |
conn.on('open', () => { | |
// now you can send data via conn | |
conn.send('*_*'); | |
}); | |
conn.on('data', (data) => { | |
console.log('from callee', data); | |
}); | |
}); | |
}; | |
// callee side | |
const another = () => { | |
const peer = new Peer('calleId', { debug: 3 }); | |
peer.on('open', (id) => { | |
peer.on('connection', (conn) => { | |
conn.on('error', (error) => { | |
console.error(error); | |
}); | |
conn.on('open', (data) => { | |
conn.send('another *_*'); | |
}); | |
conn.on('data', (data) => { | |
console.log('from initiator', data); | |
}); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have a question about the callee side. Let's say I need to respond to initiator based on what the initiator has sent to me, and not some independent message like _.
In this example, whatever the initiator has sent is just logged locally, and once the connection to initiator is open, a callee can send data.
I real-life application case, such as mine, I need to apply some sort of synchronization on callee's side, meaning
When I have data from initiator, I prepare an answer based on that data, but I don't send it until the 'open' even has fired.
Can you suggest an elegant way to synchronize?
P.S.
Yes, the 'data' is fired before 'open' 100% of times in my case.
If conn.send happens before 'open', peerjs doesn't raise any error, the initiator simply doesn't get a response data.