PeerJS simplifies peer-to-peer data, video, and audio calls.
This guide will show you the basic concepts of the PeerJS API.
Add the PeerJS client library to your webpage.
<script src="https://unpkg.com/peerjs@1.3.1/dist/peerjs.min.js"></script>
If you prefer, you can host it yourself: peerjs.min.js, or fork us on Github.
The Peer object is where we create and receive connections.
var peer = new Peer();
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. Optionally, you can pass in your own IDs to the
Peer
constructor
.
Read the Peer API reference for complete information on its options, methods, events, and error handling.
Start a data connection by calling
peer.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
peer.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 some (browser-specific) version of
navigator.getUserMedia
. When answering a call, the MediaStream is optional and if none is provided then a one-way call is
established.
Once the call is established, its
open
property is set to true.
peer.call
and the callback of the
call
event provide a MediaConnection object. The MediaConnection object itself emits a
stream
event whose callback includes the video/audio stream of the other peer.
call.on('stream', function(stream) { // `stream` is the MediaStream of the remote peer. // Here you'd add it to an HTML video/canvas element. });
Read the MediaConnection API reference for complete details on its methods and events.
PeerJS has the BinaryPack serialization format built-in. This means you can send any JSON type as well as binary Blobs and ArrayBuffers. Simply send arbitrary data and you'll get it out the other side:
conn.send({ strings: 'hi!', numbers: 150, arrays: [1,2,3], evenBinary: new Blob([1,2,3]), andMore: {bool: true} });
A small percentage of users are behind symmetric NATs. When two symmetric NAT users try to connect to each other, NAT traversal is impossible and no connection can be made. A workaround is to proxy through the connection through a TURN server. The PeerServer cloud service provides a free TURN server. This will allow your PeerJS app to work seamlessly for this situation
When creating your Peer object, pass in the ICE servers as the config key of the options hash.
var peer = new Peer({ config: {'iceServers': [ { url: 'stun:stun.l.google.com:19302' }, { url: 'turn:homeo@turn.bistri.com:80', credential: 'homeo' } ]} /* Sample servers, please use appropriate ones */ });
When you try to connect to a peer, PeerServer will hold a connection offer for up to 5 seconds before rejecting it. This is useful if you want to reconnect to a peer as it disconnects and reconnects rapidly between web pages.
You could be behind a symmetric NAT, in which case you'll need to set up a TURN server.
Another possible issue is your network blocking port 443, which the PeerServer cloud runs on. In this you must use your own PeerServer running on an appropriate port instead of the cloud service.
Data sent between the two peers do not touch any other servers, so the connection speed is limited only by the upload and download rates of the two peers. This also means you don't have the additional latency of an intermediary server.
The latency to establish a connection can be split into two components: the brokering of data and the identification of clients. PeerJS has been designed to minimize the time you spend in these two areas. For brokering, data is sent through an XHR streaming request before a WebSocket connection is established, then through WebSockets. For client identification, we provide you the ability to pass in your own peer IDs, thus eliminating the RTT for retrieving an ID from the server.