PeerJS requires two components: the PeerJS client library and the PeerServer.
The PeerServer brokers connections between PeerJS clients. Once two clients have established a connection with each other with the PeerServer's help, data is will flow between the clients directly.
Choose one of the following options:
Sign up for free cloud-hosted PeerServer service
Alternatively, PeerServer is available on GitHub and on npm:
npm install peer
Setting up the server on your own is just a few lines of code:
var PeerServer = require('peer').PeerServer;
var server = new PeerServer({ port: 9000 });
The client is where all the action is at.
<script src="http://cdn.peerjs.com/0/peer.min.js"></script>
You'll need to provide an ID. When other peers try to connect to you, they'll have to know this ID.
Also you'll need to provide either the API key for your PeerServer cloud account or your own PeerServer:
var peer = new Peer('some-id', {key: 'myapikey'});
Or if you're running your own PeerServer
var peer = new Peer('some-id', {host: 'localhost', port: 9000});
Listening for incoming connections:
peer.on('connection', function(conn){
conn.on('data', function(data) {
console.log('Got data:', data);
});
});
Create a peer connection:
var conn = peer.connect('some-id');
conn.on('open', function() {
conn.send('Hello world!');
});
PeerJS has the BinaryPack serialization format built-in. This means you can send any JSON type as well as binary Blobs and ArrayBuffers. You don't have to worry about serializing yourself. Simple put objects in on one side and get objects out on the other:
conn.send({
strings: 'hi!',
numbers: 150,
arrays: [1,2,3],
evenbinary: new Blob([1,2,3]),
andmore: {bool: true}
});
With BinaryPack, the data is never converted to strings. Everything is binary end-to-end. This results in bandwidth savings.
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.
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 is identified by two factors: the brokering of data and identifying of clients. PeerJS has been carefully coded to minimize latency in both applications. Data is brokered through an XHR streaming request before a WebSocket connection is established, then through WebSocket afterwards. Identity is self-provided and thus a new client can report identity, accept an outstanding offer, and and provide answer and thus establish the peer-to-peer connection in very few RTTs.
Note that in the infrequent case that both peers are behind symmetric NATs, this is no longer true. See below.
A very low 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 what is known as a TURN server. The PeerServer cloud service does not provide a TURN server. You'll have to find your own. You can pass a TURN server into the Peer object options. This will allow your PeerJS app to work seamlessly for this situation
A peer can connect to other peers and listen for connections.
Other peers can connect to this peer using the provided ID. If no ID is given, one will be generated by the brokering server.It's not recommended that you use this ID to identify peers, as it's meant to be used for brokering connections only. You're recommended to set the metadata
option to send other identifying information.
API key for the cloud PeerServer. This is not used for servers other than 0.peerjs.com
.
Server host. Defaults to 0.peerjs.com
. Also accepts '/'
to signify relative hostname.
Server port. Defaults to 80
.
true
if you're using SSL.Note that our cloud-hosted server and assets may not support SSL.
Configuration hash passed to RTCPeerConnection. This hash contains the ICE servers. Defaults to { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
Connects to the remote peer specified by id
and returns a data connection. Be sure to listen on the error
event in case the connection fails.
A unique label by which you want to identify this data connection. If left unspecified, a label will be generated at random. Can be accessed with dataConnection.label
.
Metadata associated with the connection, passed in by whoever initiated the connection. Can be accessed with dataConnection.metadata
. Can be any serializable type.
Can be binary
(default), binary-utf8
, json
, or none
. Can be accessed with dataConnection.serialization
.binary-utf8
will take a performance hit because of the way UTF8 strings are packed into binary format.
Whether the underlying data channels should be reliable (e.g. for large file transfers) or not (e.g. for gaming or streaming). Defaults to true
.
Calls the remote peer specified by id
and returns a media connection. Be sure to listen on the error
event in case the connection fails.
Something else
[TODO: fill this in.]
Set listeners for peer events.
Emitted when a connection to the PeerServer is established. You may use the peer before this is emitted, but messages to the server will be queued. id
is the brokering ID of the peer (which was either provided in the constructor or assigned by the server).You should not wait for this event before connecting to other peers if connection speed is important.
Emitted when a new data connection is established from a remote peer.
Emitted when a remote peer attempts to call you. The emitted mediaConnection
is not yet active; you must first answer the call (mediaConnection.answer([stream]);
). Then, you can listen for the stream
event.
Emitted when the peer is destroyed.To be extra certain that peers clean up correctly, we recommend calling peer.destroy()
on a peer when it is no longer needed.
Errors on the peer are almost always fatal and will destroy the peer. Errors from the underlying socket and PeerConnections are forwarded here.
These come in the following err.type
flavors:
The client's browser does not support some or all WebRTC features that you are trying to use.
The ID passed into the Peer constructor contains illegal characters.
The API key passed into the Peer constructor contains illegal characters or is not in the system (cloud server only).
You've already disconnected this peer and can no longer make any new connections on it.
Unable to reach the server.
An error from the underlying socket.
The underlying socket closed unexpectedly.
Close the connection to the server, leaving all existing data and media connections intact. peer.disconnected
will be set to true
.This cannot be undone; the respective peer object will no longer be able to create or receive any connections and its ID will be forfeited on the (cloud) server.
Close the connection to the server and terminate all existing connections. peer.destroyed
will be set to true
.This cannot be undone; the respective peer object will no longer be able to create or receive any connections, its ID will be forfeited on the (cloud) server, and all of its data and media connections will be closed.
The brokering ID of this peer. If no ID was specified in the constructor, this will be undefined
until the open
event is emitted.
A hash of all connections associated with this peer, keyed by the remote peer's ID.We recommend keeping track of connections yourself rather than relying on this hash.
false
if there is an active connection to the PeerServer.
true
if this peer and all of its connections can no longer be used.
Wraps WebRTC's DataChannel. To get one, use peer.connect
or listen for the connect
event.Because Chrome currently does not support reliable messaging, PeerJS uses the Reliable shim when necessary. A caveat is that with the shim you will not be able to customize serialization
when the shim is used.
data
is serialized by BinaryPack by default and sent to the remote peer.
You can send any type of data, including objects, strings, and blobs.
Closes the data connection gracefully, cleaning up underlying DataChannels and PeerConnections.
Set listeners for data connection events.
Emitted when data is received from the remote peer.
Emitted when the connection is established and ready-to-use.
Emitted when either you or the remote peer closes the data connection.
The optional label passed in or assigned by PeerJS when the connection was initiated.
Any type of metadata associated with the connection, passed in by whoever initiated the connection.
The serialization format of the data sent over the connection. Can be binary
(default), binary-utf8
, json
, or none
.
This is true if the connection is open and ready for read/write.
The ID of the peer on the other end of this connection.
For data connections, this is always 'data'
.
Wraps WebRTC's media streams. To get one, use peer.call
or listen for the call
event.
When recieving a call
event on a peer, you can call .answer
on the media connection provided by the callback to accept the call and optionally send your own media stream.
A WebRTC media stream from getUserMedia
.
Closes the media connection.
Set listeners for media connection events.
Emitted when a remote peer adds a stream
.
Emitted when either you or the remote peer closes the media connection.
Any type of metadata associated with the connection, passed in by whoever initiated the connection.
The ID of the peer on the other end of this connection.
For media connections, this is always 'media'
.
Provides a variety of helpful utilities.Only the utilities documented here are guaranteed to be present on util
. Undocumented utilities can be removed without warning. We don't consider these to be 'breaking changes.'
The current browser. This property can be useful in determining whether or not two peers can connect. For example, as of now data connections are not yet interoperable between major browsers. util.browser
can currently have the values 'Firefox', 'Chrome', 'Unsupported', or 'Supported' (unknown WebRTC-compatible browser).
A hash of WebRTC features mapped to booleans that correspond to whether the feature is supported by the current browser.Only the properties documented here are guaranteed to be present on util.supports
.
True if the current browser supports media streams and PeerConnection.
True if the current browser supports DataChannel and PeerConnection.
True if the current browser supports binary DataChannels.
True if the current browser supports reliable DataChannels.