The PeerJS library
PeerJS simplifies WebRTC peer-to-peer data, video, and audio calls.
PeerJS wraps the browser's WebRTC implementation to provide a complete, configurable, and easy-to-use peer-to-peer connection API. Equipped with nothing but an ID, a peer can create a P2P data or media stream connection to a remote peer.
Downloads [view changelog]
Setup
Include the library
<script src="http://cdn.peerjs.com/0.3/peer.js"></script>
Create a peer
Get a free API key. Your id only needs to be unique to the namespace of your API key.
var peer = new Peer('pick-an-id', {key: 'myapikey'});
// You can pick your own id or omit the id if you want to get a random one from the server.
Data connections
Connect
var conn = peer.connect('another-peers-id');
conn.on('open', function(){
conn.send('hi!');
});
Receive
peer.on('connection', function(conn) {
conn.on('data', function(data){
// Will print 'hi!'
console.log(data);
});
});
Media calls
Call
var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
getUserMedia({video: true, audio: true}, function(stream) {
var call = peer.call('another-peers-id', stream);
call.on('stream', function(remoteStream) {
// Show stream in some video/canvas element.
});
}, function(err) {
console.log('Failed to get local stream' ,err);
});
Answer
var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
peer.on('call', function(call) {
getUserMedia({video: true, audio: true}, function(stream) {
call.answer(stream); // Answer the call with an A/V stream.
call.on('stream', function(remoteStream) {
// Show stream in some video/canvas element.
});
}, function(err) {
console.log('Failed to get local stream' ,err);
});
});
PeerServer
To broker connections, PeerJS connects to a PeerServer. Note that no peer-to-peer data goes through the server; The server acts only as a connection broker.
PeerServer Cloud
If you don't want to run your own PeerServer, we offer a free cloud-hosted version of PeerServer. Start by getting a PeerServer Cloud API Key!
Run your own
PeerServer is open source and is written in node.js. You can easily run your own.
Questions?
Please report any bugs you find on the Github issues page. You can also discuss PeerJS on our Google Group or email us at [email protected].Cloud hosting powered by DigitalOcean.
Special thanks to BrowserStack for providing us browser testing services.
