PeerJS simplifies peer-to-peer data, video, and audio calls.
This guide will show you the basic concepts of the PeerJS API. If you instead just want to see a working app, see the examples page.
Add the PeerJS client library to your webpage.
<script src="http://cdn.peerjs.com/0/peer.min.js"></script>
If you prefer, you can host it yourself: peer.js or peer.min.js
The Peer object is where we create and receive connections.
var peer = new Peer({key: 'lwjd5qra8257b9'});
The 'key' we're passing in to the Peer constructor is a PeerServer cloud API key. You can use ours for now, but you should sign up for your own free key. PeerJS uses PeerServer for session metadata and candidate signaling. You can also run your own PeerServer if you don't like the cloud.
We're now ready to start making connections!
Every Peer object is assigned a random, unique, ID when it's created.
peer.on('open', function(id){ console.log('My peer id is: ' + id); });
When we want to connect to another peer, we'll need to know their peer id. You're in charge of communicating the peer ids between users of your site.
Start a data connection by calling `connect` with the peer id of the destination peer. Anytime another peer attempts to connect to your peer id, you'll receive a `connection` event.
var conn = peer.connect('dest-peer-id');
peer.on('connection', function(conn) { ... });
`peer.connect` and the callback of the `connection` event will both provide a `DataConnection` object. This object will allow you to send and receive data:
conn.on('open', function(){ // Receive messages conn.on('data', function(data){ console.log('Received', data); }); // Send messages conn.send('Hello!'); });
Read the DataConnection API reference for complete details on its methods and events.
Call another peer by calling `call` with the peer id of the destination peer. When a peer calls you, the `call` event is emitted.
Unlike data connections, when receiving a `call` event, the call must be answered or no connection is established.
// Call a peer, providing our mediaStream var call = peer.call('dest-peer-id', mediaStream);
peer.on('call', function(call){ // Answer the call providing our mediaStream call.answer(mediaStream); });
When calling or answering a call, a MediaStream should be provided. The MediaStream represents the local video (webcam) or audio stream and can be obtained with `navigator.getUserMedia`. When answering a call, the MediaStream is optional, and if none is provided then a one-way call is established.
`peer.call` and the callback of the `call` event provide a MediaConnection object. The MediaConnection object itself emits a stream event, representing the video/audio stream of the other peer.
call.on('stream', function(stream){ // stream is the MediaStream of the remote peer });
Read the MediaConnection API reference for complete details on its methods and events.