Due to browsers' incomplete support of the WebRTC DataChannel specification, many features of PeerJS have caveats. View the status page for full details.
This class is a Peer, which can connect to other peers and listen for connections. It is an EventEmitter
.
id
String. The id by which this peer will be identified when other peers try to connect to it. If no id is given, one will be generated by the server. Note that this ID is mainly used for brokering and that it is not recommended that you use it to identify peers. Also note that you can set a metadata
option to send other identifying information.options
Objectkey
String. API key for cloud PeerServer. Is not used for servers other than cloud.peerjs.com
host
String. Server host. Default cloud.peerjs.com
. Also accepts '/'
for relative hostname.port
Number. Server port. Default 80
config
Object. Configuration hash passed to RTCPeerConnection
. This hash contains the ICE servers. Default { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
debug
Boolean. Prints verbose log messages. Default false
Construct a new Peer object.
The Peer object is used to connect to other Peer clients and also to receive connections from other clients.
The first argument is the id that other peers will use to connect to this peer, thus it must be unique for the given key
(if you're using PeerServer cloud) or server.
In the options, either a PeerServer Cloud key
must be provided or host
and port
for your own PeerServer. Note that the server is only for brokering connections and does not proxy data between peers.
The config
object is passed straight into instances of RTCPeerConnection
. For compatibility with symmetric NATs, you can provide your own TURN server. By default the STUN server provided by Google is used.
The type of browser the client is on. Currently WebRTC DataChannels are not interoperable so different browser types should not be connected.
The given id of this peer.
If no id was specified in the constructor, this value will be undefined
util the open
event fires.
A hash of all current connections with the current peer. Keys are ids and values are hashes of label => DataConnection
pairs.
You are recommended to keep track of connections yourself rather than to manipulate this hash.
Connects to the remote peer specified by id
.
This function can be called multiple times for multiplexed connections between two peers. In Firefox however this functionality is only available before the first connection is established.
Returns a DataConnection
object.
id
String. The id of the remote peer to connect to.options
Object.label
Optional label for the underlying DataChannel, to differentiate between DataConnections between the same two peers. If left unspecified, a label will be assigned at random.metadata
Optional metadata to pass to the remote peer. Can be any serializable type.serialization
String, which can be binary
, binary-utf8
, json
, or none
. This will be the serialization format of all data sent over the P2P DataConnection. Defaults to binary
.reliable
Boolean, which if true
activates experimental reliable transfer in Chrome (while waiting for actual reliable transfer to be implemented in Chrome). Defaults to false
until Chrome implements reliable/large data transfer. Defaults to true in Firefox.Before writing to / data will be emitted from the DataConnection
object that is returned, the open
event must fire. Also the error
event should be checked in case a connection cannot be made.
Close the connection to the server and terminate all connections.
Warning: 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, leaving all existing DataConnections intact.
Warning: 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.
Is false if there is an active connection to the PeerServer.
Is true if this peer is destroyed and can no longer be used.
function (connection, meta) { }
When a new connection is established from another peer to this peer, the DataConnection
object is emitted with this event. The meta
argument contains whatever metadata values passed into peer.connection(...)
by the remote peer.
Note: the open
event must fire on the DataConnection
before it is ready to read/write.
function(id) { }
Fired when the PeerServer connection is succesfully, fully, open. This event does not need to fire before creating or receiving connections. You should not wait for open before connecting to other peers or expecting to receive connections if connection speed is important.
id
is the id of this Peer
object, either provided in the constructor, or generated automatically by the PeerServer.
function (error) { }
Emitted when an unexpected event occurs. Errors on the Peer are always fatal. Errors from the underlying socket and PeerConnections are forwarded here.
The error
object also has a type
parameter that may be helpful in responding to client errors properly:
browser-incompatible
: The client's browser does not support some or all WebRTC features that you are trying to use.
invalid-id
: The ID passed into the Peer constructor contains illegal characters.
invalid-key
: The API key passed into the Peer constructor contains illegal characters or is not in the system (cloud server only).
unavailable-id
: The ID passed into the Peer constructor is already taken.
firefoxism
: The operation you're trying to perform is not supported in firefox.
ssl-unavailable
: PeerJS is being used securely, but the cloud server does not support SSL. Use a custom PeerServer.
Errors types that shouldn't regularly appear:
server-error
: Unable to reach the server.
socket-error
: An error from the underlying socket.
socket-closed
: The underlying socket closed unexpectedly.
(The Peer object is destroyed after one of the errors above are emitted.)
server-disconnected
: A Peer that has been disconnected is being used to try to connect.
function () { }
Emitted when the Peer object has closed its connection with PeerServer so no more remote peer connections can be made or received.
To be extra certain that Peer objects clean up cleanly (and because it takes the WS server and DataChannel some time to realize that a Peer has disconnected), it is best to call destroy()
on a Peer when it is no longer needed.
This class is the interface two communicate between two peers. It is an EventEmitter
.
There is no constructor. A DataConnection
object must be obtained in the callback of peer.connect(...)
when initiating a peer-to-peer connection or emitted in the peer.on('connection', ...)
event when receiving a connection.
(CHROME ONLY. Firefox has reliable transport built in and reliable transfer is the default option.) Simply pass in reliable: true
when calling .connect(...)
. This module is experimental, temporary, and exists here: https://github.com/michellebu/reliable
Caveat: With reliable enabled in Chrome, you can no longer customize the serialization format used for data transfer.
The id of the remote peer this connection is connected to.
Whether the connection is open (ready for read and write).
The metadata passed in when the connection was created with peer.connect(...)
.
The optional label passed in or assigned by PeerJS when the connection was created with peer.connect(...)
.
The serialization format of the connection. Can be binary
, binary-utf8
, json
, or none
for no serialization. Default serialization format is binary
.
Note: binary-utf8
will take a performance hit because of the way utf8 strings are packed into binary.
Accepts data of any JSON type or binary type.
To configure which serialization format to use, specify binary
, binary-utf8
, json
, or none
as the serialization
property of the options
object in peer.connect(...)
.
Data is serialized using BinaryPack (binary
) by default and then sent to the remote peer.
Gracefully closes the connection.
function (data) { }
Emitted when data is received from the remote peer.
The data
parameter contains values exactly as put into the connection.send(...)
. Binary types will have been deserialized to ArrayBuffer
.
function () { }
Emitted when the connection is established and ready for writing. data
from the remote peer will also start to be emitted.
function (error) { }
If the connection emits an error, this event is emitted (errors from the underlying DataChannel
are forwarded here).
error
is an Error
object.
function () { }
Is emitted when the connection is closed.
The close
event is also emitted when the remote peer closes the connection.
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