PeerJSは、WebRTCを利用したピア·ツー·ピアのデータ、ビデオ、オーディオ通信を簡単に実現することができます。このドキュメントでは、PeerJS APIの基本的な使い方を紹介します。PeerJSを用いた実装例をご覧になりたい方は, サンプル ページを御覧ください。
このドキュメントは、NTTコミュニケーションズが提供するクラウドサービス「SkyWay」にて利用できるようにカスタマイズしたPeerJSを対象としています。
PeerJSクライアントライブラリをあなたのアプリケーションにインクルードしてください。
<script src="https://skyway.io/dist/0.3/peer.js"></script>
PeerJSライブラリ(peer.js, peer.min.js)はあなたのサーバ上に設置することができます。 ソースコードはGithubからforkする事ができます。
Peerオブジェクトは、Peerコネクションを生成、受信する為に利用します。
var peer = new Peer({key: 'APIKEY'});
Peerのコンストラクタに渡す'APIKEY'は、SkyWayのAPIキーです。APIキーの申し込みを行うことで無料で取得することができます。APIキー申込時には利用ドメインを申請していただきます。APIキーは申請したドメインからのみ利用可能です。
PeerJSのセッション情報交換やシグナリングに利用するサーバを、自身で構築することもできます。 詳しくはpeerjs-serverをご覧ください。
これで利用するための準備はすべて整いました!
Peerオブジェクトは生成時、ランダムなID(以下、PeerID)が付与されます。
peer.on('open', function(id) {
console.log('My peer ID is: ' + id);
});
他のPeerと接続したい場合は、接続先のPeerIDが必要になります。
RestAPIを利用して接続先のPeerIDを入手するか、何らかの仕組みでPeerIDを交換してください。Peer constructorのオプションに自身のPeerIDを指定すると、この処理を省略することができます。
その他のオプション、メソッド、イベント、エラー処理などの詳細は、Peer API リファレンスをお読みください。
相手のPeerIDを指定してpeer.connectを実行するとData connectionを開始します。相手から接続要求はいつでもconnection イベントを利用して受け取ることができます。
var conn = peer.connect('dest-peer-id');peer.on('connection', function(conn) { ... });peer.connectとconnectionイベントのコールバックではDataConnectionオブジェクトを提供します。このオブジェクトを使用してデータの送受信を行うことができます。
conn.on('open', function() {
// メッセージを受信
conn.on('data', function(data) {
console.log('Received', data);
});
// メッセージを送信
conn.send('Hello!');
});
メソッドとイベントの詳細は、DataConnection API リファレンスをご覧ください。
相手のPeerIDを指定してpeer.callを実行することで、その相手を呼び出すことができます。相手があなたを呼び出した場合、 callイベントが発生します。
callイベントを受信した時は、必ずそのイベントに応答する必要があります。応答しなければ接続は確立しません。
// 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);
});相手を呼び出す時、または、呼び出しに応答する時には、MediaStreamを提供する必要があります。
MediaStreamにはビデオストリーム(ウェブカメラの映像)やオーディオストリームなどがあり、navigator.getUserMediaによって取得することができます。取得できる内容はブラウザによってことなります。
尚、呼び出しに応答する時のMediaStreamは必須ではありません。もし応答時にMediaStreamをセットしなければ、一方向の通話が確立されます。
通話が確立されると、openプロパティにtrueがセットされます。
peer.call と call イベントのコールバックではMediaConnectionオブジェクトを提供します。
MediaConnectionオブジェクトはstream イベントをキャッチすることができます。streamイベントのコールバックには相手の映像/音声ストリームが含まれます。
call.on('stream', function(stream) {
// `stream` is the MediaStream of the remote peer.
// Here you'd add it to an HTML video/canvas element.
});
詳しくは MediaConnection API reference をご覧ください。
APIキー毎のアクティブなPeerIDを取得します。
Request : https://skyway.io/active/list/APIKEY Response : [peerid1,peerid2,peerid3,peerid4,.....]
APIキー毎のアクティブなPeerIDの数を取得します。
Request : https://skyway.io/active/count/APIKEY
Response : {"name":"active_session","count":0,"api_key":"APIKEY"}
SkyWay WebAPIはAPIキー申請時に申請していただいたドメインからのみアクセスが可能です。
PeerJSは BinaryPackシリアライゼーションフォーマットを利用しています。JSONやバイナリBlobs、ArrayBuffersなど様々なデータを簡単な手順で送受信することができます。
conn.send({
strings: 'hi!',
numbers: 150,
arrays: [1,2,3],
evenBinary: new Blob([1,2,3]),
andMore: {bool: true}
});
シンメトリックNATの内側にいるクライアント同士はNATを超えることができないため、通信することができません。
ただし、TURNサーバを利用して接続を中継すれば回避することができます。TURNサーバは提供していないため必要であれば別途用意してください。
TURNサーバの情報は、Peerオブジェクトのオプションで指定することができます。
Peerオブジェクトを生成する際、オプションのiceServersにURL等の情報を設定してください。
var peer = new Peer({
config: {'iceServers': [
{ url: 'stun:stun.skyway.io:3478' },
{ url: 'turn:homeo@turn.bistri.com:80', credential: 'homeo' }
]} /* Sample servers, please use appropriate ones */
});
WebRTC仕様との互換性並びにブラウザの対応状況はこちらをご覧ください。尚、SkyWay対応版のPeerJSについては、動作に差異がある可能性があります。
ピアに接続できない場合はPeerServerにて接続要求を5秒間保持します。ピアが一時的に再接続するような場合、コネクションを切らずに保持することができます。尚、SkyWayは現時点ではこの機能に対応していません。
ピア同士がシンメトリックNATの内側にいる可能性があります。この場合はTURNサーバを利用してください。
ファイアウォール等でUDPのポート3478(STUNサーバへの問い合わせに必要)をブロックしているかもしれません。STUNサーバへの問い合わせが可能な状況でご利用ください。
ピア同士のデータのやり取りはサーバを経由しないため、それが原因となる遅延などは発生しません。ピア同士の処理性能やネットワーク環境に依存します。
ピア同士のコネクション確立に関する遅延は、セッション情報の中継(以下、シグナリング)とユーザの識別という2つに分類できます。PeerJSでは、シグナリングの時間を短縮するために、XHRストリーミングリクエストでデータを送った後、WebSocketで送ります。ユーザの識別に関しては手動でIDを指定することで、サーバ側にてIDを生成する際のRTT(Round-Trip delay Time)を短縮することができます。尚、SkyWayに関してはXHRでの接続に現時点では対応していません。
本ドキュメントはhttp://peerjs.com/docs/を元に、NTTコミュニケーションズが提供するSkyWayを利用するための情報等を追記し公開しています。ドキュメント原本に関する個別問い合わせには応じることができませんので、予めご了承ください。
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.PeerServer cloud runs on port 9000. Please ensure it is not blocked or consider running your own PeerServer instead.
Server host. Defaults to 0.peerjs.com. Also accepts '/' to signify relative hostname.
Server port. Defaults to 80.
The path where your self-hosted PeerServer is running. Defaults to '/'.
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 any custom ICE/TURN server configuration. 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 false.Setting reliable to true will use a shim for incompatible browsers (Chrome 30 and below only) and thus may not offer full performance.
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.
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 and can no longer accept or create any new connections. At this time, the peer's connections will all be closed. To be extra certain that peers clean up correctly, we recommend calling peer.destroy() on a peer when it is no longer needed.
Emitted when the peer is disconnected from the signalling server, either manually or because the connection to the signalling server was lost. When a peer is disconnected, its existing connections will stay alive, but the peer cannot accept or create any new connections. You can reconnect to the server by calling peer.reconnect().
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.
You've already disconnected this peer from the server and can no longer make any new connections on it.
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).
Lost or cannot establish a connection to the signalling server.
Unable to reach the server.
An error from the underlying socket.
The underlying socket closed unexpectedly.
Native WebRTC errors.
Close the connection to the server, leaving all existing data and media connections intact. peer.disconnected will be set to true and the disconnected event will fire.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.
Attempt to reconnect to the server with the peer's old ID. Only disconnected peers can be reconnected. Destroyed peers cannot be reconnected. If the connection fails (as an example, if the peer's old ID is now taken), the peer's existing connections will not close, but any associated errors events will fire.
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.
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.Firefox does not yet support this event.
A reference to the RTCDataChannel object associated with the 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.
This is true if the connection is open and ready for read/write.
A reference to the RTCPeerConnection object associated with the connection.
The ID of the peer on the other end of this connection.
Whether the underlying data channels are reliable; defined when the connection was initiated.
The serialization format of the data sent over the connection. Can be binary (default), binary-utf8, json, or none.
For data connections, this is always 'data'.
The number of messages queued to be sent once the browser buffer is no longer full.
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.Firefox does not yet support this event.
Whether the media connection is active (e.g. your call has been answered). You can check this if you want to set a maximum wait time for a one-sided call.
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.