PeerJS simplifies peer-to-peer data, video, and audio calls.
This guide will show you the basic concepts of the PeerJS API. If you learn better from seeing a working app, see the examples at the bottom of the page.
This document is for NTT Communication's cloud service "SkyWay", a customized version of PeerJS.
Add the PeerJS client library to your webpage.
<script src="https://skyway.io/dist/0.3/peer.min.js"></script>
If you prefer, you can host it yourself: peer.js, peer.min.js, or fork us on Github.
The Peer object is where we create and receive connections.
var peer = new Peer({key: 'APIKEY'});
You can 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. 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.
Gets a list of active PeerID's connecting with the API key.
peer.listAllPeers(function(list){ // e.g. Add retrieved Peer ID list to userList array. for(var cnt = 0;cnt < list.length;cnt++){ userList.push(list[cnt]); } });
The SkyWay Rest API can only be accessed from the domain registered with the API key.
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} });
Depending on the value of serialization, the data that can be sent between each of the platforms (JavaScript, iOS, and Android) changes. See this chart for details.
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. You'll have to find your own. If you wish to use SkyWay's TURN server, you can apply here. You can pass a TURN
server into the Peer
object options. 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.skyway.io.com:3478' }, { url: 'turn:homeo@turn.bistri.com:80', credential: 'homeo' } ]} /* Sample servers, please use appropriate ones */ });
This option doesn't need to be set if you're using SkyWay's TURN server.
We keep an frequently-updated catalogue of WebRTC compatibility information and caveats here.
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.
Data sent between the two peers do not touch any other servers except for use of turn server, 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.
Discuss SkyWay on SkyWay Technical Forum Google Group.
Discuss PeerJS on PeerJS Google Group.
This document is based on http://peerjs.com/docs/ and provides additional information necessary to use NTT Communication's SkyWay service. We cannot respond to inquiries regarding the original document.
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 skyway.io
.SkyWay cloud runs on port 443. Please ensure it is not blocked.
Server host. Defaults to skyway.io
. Also accepts '/'
to signify relative hostname.
Server port. Defaults to 443
.
true
if you're using SSL. Defaults to true since skyway.io uses SSL.
true
if you're using SkyWay's TURN server. Defaults to true
. You must apply here to use this feature.
Configuration hash passed to RTCPeerConnection. This hash contains any custom ICE/TURN server configuration. Defaults to { 'iceServers': [{ 'url': 'stun:stun.skyway.io:3478' }] }
. It is not necessary to set iceServers if you're using SkyWay's TURN server.
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.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.
Get an array of PeerIDs of users connected with the same API key.
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.Depending on the value of serialization, the data that can be sent between each of the platforms (JavaScript, iOS, and Android) changes. See this chart for details.
The data to send.
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.
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'
.
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.
SkyWay simplifies peer-to-peer data, video, and audio calls using WebRTC."SkyWay iOS SDK" is a framework that enables using SkyWay in iOS apps.This guide will show you the basic concepts of the SkyWay iOS SDK. If
you learn better from seeing a working app, see the examples
Add the following libraries and frameworks to your Xcode project.
AudioToolbox.framework AVFoundation.framework CoreMedia.framework CoreVideo.framework VideoToolbox.framework CoreGraphics.framework Foundation.framework GLKit.framework SystemConfiguration.framework libc++.tbd libstdc++.6.0.9.tbd libsqlite3.tbd libicucore.tbd
Add SkyWay.framework to your Xcode project and import header file. Make sure you set "Linking > Other Linker Flags = -ObjC" in Build Settings.
#import <SkyWay/SKWPeer.h>
※This SDK doesn't support Bitcode because of our internal library. On Xcode7, please set "Build Options > Enable Bitcode = NO" in Build Settings.
The SKWPeer object is where we create and receive connections.
SKWPeerOption* options = [[SKWPeerOption alloc] init]; options.key = @"{APIKEY}"; options.domain = @”{DOMAIN}”; SKWPeer* peer = [[SKWPeer alloc] initWithOptions:options];
You can sign up for your own free key. You will need to register a domain when you sign up for an API key. You will only be able to use the API key from the registered domains.
You can also run your own PeerServer for session metadata and candidate signaling, if you don't like the cloud.
We're now ready to start making connections!
Every SKWPeer object is assigned a random, unique ID when it's created.
[peer on:SKW_PEER_EVENT_OPEN callback:^(NSObject* obj) { if (YES == [obj isKindOfClass:[NSString class]]) { NSString* ownId = (NSString *)obj; } }];
When we want to connect to another peer, we'll need to know their peer id. Use the listAllPeers method of the SKWPeer class to get the remote PeerId or communicate PeerIds out of bound through some other method. Optionally, you can pass in your own IDs to the SKWPeer constructor.
Read the Peer API reference for complete information on its options, methods, events, and error handling.
Start a data connection by calling connectWithId
with the peer ID of the destination peer. Anytime another peer attempts to connect to your peer
ID, you'll receive a SKW_PEER_EVENT_CONNECTION
event.
SKWDataConnection* dataConnection = [peer connectWithId:'dest-peer-id'];
[peer on:SKW_PEER_EVENT_CONNECTION callback:^(NSObject* dataConnection){ ... }];
connectWithId
method of the SKWPeer class and the callback of the
SKW_PEER_EVENT_CONNECTION
event will both provide a
SKWDataConnection
object. This object will allow you to send and receive data:
[dataConnection on:SKW_DATACONNECTION_EVENT_OPEN callback:^(NSObject* obj){ ... }]; [dataConnection on:SKW_DATACONNECTION_EVENT_DATA callback:^(NSObject* obj) { // Receive String messages NSString* strData = nil; if ([obj isKindOfClass:[NSString class]]) { strData = (NSString *)obj; } }]; // Send messages BOOL bResult = [dataConnection send:@"Hello SkyWay!"]; if (NO == bResult) { // Failed } else { // Succeeded }
Read the DataConnection API reference for complete details on its methods and events.
Call another peer by calling callWithId
with the peer ID of the destination peer. When a peer calls you, the SKW_PEER_EVENT_CALL
event is emitted.
Unlike data connections, when receiving a SKW_PEER_EVENT_CALL
event, the call must be answered or no connection is established.
SKWMediaConnection* mediaConnection = [peer callWithId:dest-peer-id stream:mediaStream];
[peer on:SKW_PEER_EVENT_CALL callback:^(NSObject* mediaConnection){ [mediaConnection answer:mediaStream]; }];
When calling or answering a call, a MediaStream should be provided.
MediaStream represents the local video (webcam) or audio stream and can be
obtained SKWNavigator getUserMedia
method. 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 isOpen
property is set to YES.
callWithId
method of the SKWPeer class and the callback of the SKW_PEER_EVENT_CALL
event provide a MediaConnection object. The MediaConnection object itself emits a SKW_MEDIACONNECTION_EVENT_STREAM
event whose callback includes the video/audio stream of the other peer.
[mediaConnection on:SKW_MEDIACONNECTION_EVENT_STREAM callback:^(NSObject* stream) { // `stream` is the SKWMediaStream of the remote peer. // Here you'd add it to SKWVideo. }];
Read the MediaConnection API reference for complete details on its methods and events.
Gets a list of active PeerID's connecting with the API key.
[peer listAllPeers:^(NSArray* aryPeers) { for (NSString* strPeer in aryPeers) { ... } }];
The SkyWay Rest API can only be accessed from the domain registered with the API key.
When serialization is set to binary or binary-utf8, MessagePack serialization format is used. You can easily send NSData*, NSString*, NSNumber*, NSDictionary*, NSArray*. It is not possible for an NSDictionary or NSArray to contain another NSDictionary/NSArray.
NSDictionary* dctData = @{ @"1": @"one", @"2": @"two", @"3": @"three", @"4": @"four", @"5": @"five", }; BOOL bResult = [_dataConnection send:dctData];
Depending on the value of serialization, the data that can be sent between each of the platforms (JavaScript, iOS, and Android) changes. See this chart for details.
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. You'll have to find your own. If you wish to use SkyWay's TURN server, you can apply here. You can pass a TURN server into the Peer
object options. 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.
SKWIceConfig* configStun = [[SKWIceConfig alloc] init]; configStun.url = @"stun:stun.skyway.io:3478"; SKWIceConfig* configTurn = [[SKWIceConfig alloc] init]; configTurn.url = @"turn:homeo@turn.bistri.com:80"; configTurn.credential = @"homeo"; // Sample servers, please use appropriate ones SKWPeerOption* options = [[SKWPeerOption alloc] init]; option.config = @[configStun,configTurn]; SKWPeer* peer = [[SKWPeer alloc] initWithOptions:options];
This option doesn't need to be set if you're using SkyWay's TURN server.
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.
Data sent between the two peers do not touch any other servers except for use of turn server, 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.
iOS 7+
iPhone 5+、iPodTouch 6+、iPad 2+
Discuss SkyWay on SkyWay Technical Forum Google Group.
This document is based on http://peerjs.com/docs/ and provides additional information necessary to use NTT Communication's SkyWay service. We cannot respond to inquiries regarding the original document.
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 themetadata
option to send other identifying information.
The options object.
Connects to the remote peer specified by id
and returns a SKWDataConnection. Be sure to listen on the error
event in case the connection fails.
The options object.
Calls the remote peer specified by id
で and returns a SKWMediaConnection.Be sure to listen on the error
event in case the connection fails.
The caller's media stream
The options object.
Set listeners for SKWPeerEvent.
Specifies the event type.
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.ownId
is the brokering ID of the peer (which was either provided in the SKWPeer 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. The callback function parameter is an SKWDataConnection object.
Emitted when a remote peer attempts to call you. The callback function parameter is an SKWMediaConnection object. 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 isdestroyed 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 isdisconnected from the signalling server.
The callback function parameter is an SKWPeerError object. Errors on the peer are almost always fatal and will destroy the peer. Errors from the underlying socket and PeerConnections are forwarded here.
Specifies the Block to call when the event is triggered.
Close the connection to the server, leaving all existing data and media connections intact.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.
Reconnects to the signaling server. Connects using the same peerID. Only succeeds if disconnected using disconnect
. Will not work if disconnected using destroy
.
Close the connection to the server and terminate all existing connections.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 and its ID will be forfeited on the (cloud) server. Also closes all MediaConnections and DataConnections.
Get an NSArray of PeerIDs of users connected with the same API key.
The brokering ID of this peer. If no ID was specified in the SKWPeer class, this will be undefined
until theopen
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.
NO
if there is an active connection to the PeerServer.
YES
if this peer and all of its connections can no longer be used.
Specify connection settings.
API key for the cloud PeerServer.
The domain registered with the API key on the SkyWay developer's dashboard.
Server host. Defaults to skyway.io
.
Server port. Defaults to 443
.
The path where your self-hosted PeerServer is running. Defaults to '/'
.
YES
if you're using SSL. Defaults to YES
since skyway.io uses SSL.
YES
if you're using SkyWay's TURN server. Defaults to YES
. You must apply here to use this feature.
Configuration SKWIceConfig
NSArray*.Defaults to { 'iceServers': [{ 'url': 'stun:stun.skyway.io:3478' }] }. It is not necessary to set iceServers if you're using SkyWay's TURN server.
Prints log messages depending on the debug level passed in. Defaults to SKW_DEBUG_LEVEL_NO_LOGS
.
Prints no logs.
Prints only errors.
Prints errors and warnings.
Prints all logs.
Specify STUN/TURN server settings.
The STUN/TURN server url.
Use when a user name is required.
Use when a password is required.
Specify options for connecting to peers.
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 withdataConnection.label
Metadata associated with the connection, passed in by whoever initiated the connection. Can be accessed withdataConnection.metadata
.
The data serialization format. Default is BINARY. This value changes what type of data can be sent using dataConnection.send
. The value can be obtained using dataConnection.serialization
.
Set serialization type:binary
Set serialization type:binary-utf8
Set serialization type:json
Set serialization type:none
Whether the underlying data channels should be reliable (e.g. for large file transfers) or not (e.g. for gaming or streaming). Defaults to NO
Specify options for calling peers.
Any type of metadata associated with the connection, passed in by whoever initiated the connection.
Obtained when an ”error” event occurs. If the OS gives error info, it can be found in the error property.
Enumerated error types.
No error has occurred
The client does not support some or all WebRTC features that you are trying to use.
The ID passed into the SKWPeer constructor contains illegal characters.
The API key passed into the SKWPeer 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.
Network error between signalling server.
Error about WebRTC.
error message
Error information object from OS.
Wraps WebRTC's DataChannel. To get one, use SKWPeer connectWithId
or listen for the SKW_PEER_EVENT_CONNECTION
event.
Sends data to the remote peer. The processing method changes depending on the serialization
property. Depending on the value of serialization, the data that can be sent between each of the platforms (JavaScript, iOS, and Android) changes. See this chart for details.
The data to send.
Closes the data connection gracefully, cleaning up underlying DataChannels and PeerConnections.
Set event callback for SKWDataConnection events.
Data connection event types.
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 callback function parameter is aSKWPeerError parameter.
Specifies the Block to call when the event is triggered.
The number of messages queued to be sent once the browser buffer is no longer full.
A reference to the SKWDataChannel object associated with the connection.
A unique label by which you want to identify this data connection. If left unspecified, a label will be generated at random.
Any type of metadata associated with the connection, passed in by whoever initiated the connection.
Is YES
if the connection is open and ready for reading and writing.
The RTCPeerConnection object tied to the connection.
The ID of the peer on the other end of this connection.
Whether the underlying data channels should be reliable. Is set when the connection is opened.
The serialization format to use when sending data. Is set when the connection is opened.
binary
binary-utf8
For data connections, this is always 'data'
.
Wraps WebRTC's media streams. Obtained from Peer.callWithId
or the SKW_PEER_EVENT_CALL
event.
Answer media connections obtained from a call
event. You can set your own media stream as the parameter.
SKWMediaStream
obtained from SKWNavigator.getUserMedia.
Closes the media connection.
Set listeners for SKWMediaConnectionEnum event.
MediaConnection event types.
Emitted when a remote peer adds a stream
.
Emitted when either you or the remote peer closes the media connection.
The class of callback arguments isSKWPeerError.
Specifies the Block to call when the event is triggered.
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'
.
close MedisStream.
Gets the number of VideoTracks added to the MediaStream.
Sets the play state of VideoTracks in a MediaStream.
Gets the play state of the VideoTrack.
The index of the VideoTrack. VideoTrack indexes are 0 or greater.
The number of Audio tracks added to media stream.
Set the play state of audio track added to media stream.
Get audio track play state.
The index of the AudioTrack. AudioTrack indexes are 0 or greater.
In case of using iOS device's local media stream, set used camera
Set used camera position.
Use camera found first. The order depends on the system.
Use back camera.
Use front camera.
In case of using iOS device's local media stream, get used camera
Get used camera position.
Camera position is unspecified.
Camera position is back.
Camera position is front.
Change camera if possible while using iOS device's local media stream. Returns true
if it successfully changes camera, false
otherwise.
The object to display the video.
Add mediastream and Track No, as a media source to the SKWVideo object.
mediastream to add.
The index of the VideoTrack. VideoTrack indexes are 0 or greater.
Remove mediastream and Track No, as a media source from the SKWVideo object.
mediastream to remove.
The index of the VideoTrack. VideoTrack indexes are 0 or greater.
Callback called when video size changes.
Specifies the Block to call when the event is triggered.
Options for the SKWNavigator.getUserMedia.
Set the video. YES
enable the video, NO
disable the video. Defaults to YES
.
Sets the audio. YES
enable the audio, NO
disable the audio. Defaults to YES
.
Sets the camera mode. Defaults to SKW_CAMERA_MODE_SWITCHABLE
.
You can change the camera during the transmission of the media stream.
You can change the width/height property.
Set camera. Defaults to SKW_CAMERA_POSITION_FRONT. Enable when the cameraMode is SKW_CAMERA_MODE_ADJUSTABLE
.
Use camera found first. The order depends on the system.
Use back camera. If it's not found, use camera found first.
Use front camera. If it's not found, use camera found first.
Set the width pixel maximum limit. Defaults to 640
.
Valid values for maxWidth, minWidth, maxHeight, minHeight are shown below. In case of setting invalid value or combination, values will be set to defaults.max (Width x Height): 640x480, 352x288
min (Width x Height): 192x144, 352x288, 512x384, 640x480
Set the width pixel minimum limit. Defaults to 192
. Enable when the cameraMode is SKW_CAMERA_MODE_ADJUSTABLE
.
Set the height pixel maximum limit. Defaults to 480
. Enable when the cameraMode is SKW_CAMERA_MODE_ADJUSTABLE
.
Set the height pixel minimum limit. Defaults to 144
. Enable when the cameraMode is SKW_CAMERA_MODE_ADJUSTABLE
.
SkyWay simplifies peer-to-peer data, video, and audio calls using WebRTC."SkyWay Android SDK" is a framework that enables using SkyWay in Android apps.This guide will show you the basic concepts of the SkyWay Android SDK. If
you learn better from seeing a working app,see the examples
Add the following settings to your manifest file.
<uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
Add SkyWay.aar to your application and import class files.
#import io.skyway.Peer.*
The Peer object is where we create and receive connections.
PeerOption options = new PeerOption(); options.key = "{APIKEY}"; options.domain = "{DOMAIN}"; Peer peer = new Peer(options);
You can sign up for your own free key. You will need to register a domain when you sign up for an API key. You will only be able to use the API key from the registered domains.
You can also run your own PeerServer for session metadata and candidate signaling, 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(Peer.PeerEventEnum.OPEN, new OnCallback(){ public void onCallback(Object object){ if (object instanceof String){ string id = (String) object; } } });
When we want to connect to another peer, we'll need to know their peer id. PeerクラスのlistAllPeers method of the SKWPeer class to get the remote PeerId or communicate PeerIds out of bound through some other method. 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 connect(peerId)
with the peer ID of the destination peer. Anytime another peer attempts to connect to your peer
ID, you'll receive a PeerEventEnum.CONNECTION
event.
DataConnection dataConnection = peer.connect('dest-peer-id');
peer.on(Peer.PeerEventEnum.CONNECTION,new OnCallback(){ public void onCallback(Object object){ ... } });
Peer connect(peerId)
and the callback of the
PeerEventEnum.CONNECTION
event will both provide a
DataConnection
object. This object will allow you to send and receive data:
dataConnection.on(DataEventEnum.DATA,new OnCallback(){ public void onCallback(Object object){ // Receive String messages String strValue = null; if (object instanceof String){ strValue = (String)object; } } }); // Send messages Bool bResult = dataConnection.send("Hello SkyWay!"); if(NO == bResult){ // Failed }else{ // Succeeded }
Read the DataConnection API reference for complete details on its methods and events.
Call another peer by calling call(peerId)
with the peer ID of the destination peer. When a peer calls you, the PeerEventEnum.CALL
event is emitted.
Unlike data connections, when receiving a PeerEventEnum.CALL
event, the call must be answered or no connection is established.
MediaConnection mediaConnection = peer.call('dest-peer-id',mediaStream);
peer.on(Peer.PeerEventEnum.CALL,new OnCallback(){ public void onCallback(Object object){ mesiaConnection.answer(mesiastream); } });
When calling or answering a call, a MediaStream should be provided.
MediaStream represents the local video (webcam) or audio stream and can be
obtained Navigator getUserMedia
method. 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 isOpen
property is set to true.
Peer call(peerId)
and the callback of the PeerEventEnum.CALL
event provide a MediaConnection object. The MediaConnection object itself emits a MediaEventEnum.STREAM
event whose callback includes the video/audio stream of the other peer.
mediaConnection.on(event, new OnCallback(){ puclic void onCallback(Object object){ // `stream` is the MediaStream of the remote peer. // Here you'd add it to Canvas. } });
Read the MediaConnection API reference for complete details on its methods and events.
Gets a list of active PeerID's connecting with the API key.
peer.listAllPeers(new OnCallback(){ public void onCallback(Object object){ if (!(object instanceof JSONArray)){ return; } JSONArray peers = (JSONArray) object; } });
The SkyWay Rest API can only be accessed from the domain registered with the API key.
When serialization is set to binary or binary-utf8, MessagePack serialization format is used. You can use Byte, Short, Integer, Long, Float, Double, byte[], String, ByteBuffer, List, Map. It is not possible for a Map or List to contain another Map or List.
HashMap< String, String > map = new HashMap<>(); for (int i = 0 ; 5 > i ; i++){ String strKey = String.format("%d", i); String strValue = String.format("Value:%d", i); map.put(strKey, strValue); } Boolean bResult = _data.send(map);
Depending on the value of serialization, the data that can be sent between each of the platforms (JavaScript, iOS, and Android) changes. See this chart for details.
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. You'll have to find your own. If you wish to use SkyWay's TURN server, you can apply here. You can pass a TURN server into the Peer
object options. 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.
PeerOption options = new PeerOption(); // Sample servers, please use appropriate ones IceConfig configTurn = new IceConfig(); configTurn.url = "turn:homeo@turn.bistri.com:80"; configTurn.credential = "homeo"; options.config = {configStun,configTurn}; Peer peer = new Peer(options);
This option doesn't need to be set if you're using SkyWay's TURN server.
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.
Data sent between the two peers do not touch any other servers except for use of turn server, 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.
Android 4.0.3+
Nexus 5 2013、Nexus 6 2015、Xperia Z1 2013、ZenPhone 2014、Galaxy S5
Discuss SkyWay on SkyWay Technical Forum Google Group.
This document is based on http://peerjs.com/docs/ and provides additional information necessary to use NTT Communication's SkyWay service. We cannot respond to inquiries regarding the original document.
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 themetadata
option to send other identifying information.
The options object.
Connects to the remote peer specified by id
and returns a DataConnection. Be sure to listen on the error
event in case the connection fails.
The options object.
Calls the remote peer specified by id
and returns a MediaConnection.Be sure to listen on the error
event in case the connection fails.
The caller's media stream
The options object.
Set listeners for PeerEvent.
Specifies the event type.
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.ownId
is the brokering ID of the peer (which was either provided in the Peer 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. The callback function parameter is a DataConnection object.
Emitted when a remote peer attempts to call you. The callback function parameter is a MediaConnection object. 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 isdestroyed 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 isdisconnected from the signalling server.
Specifies the callback function to call when the event is triggered.
Close the connection to the server, leaving all existing data and media connections intact.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.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 and its ID will be forfeited on the (cloud) server. Also closes all data and media connections.
Get an JSONArray of PeerIDs of users connected with the same API key.
The brokering ID of this peer. If no ID was specified inPeer class, this will be undefined
until theopen
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.
Specify connection settings.
API key for the cloud PeerServer.
The domain registered with the API key on the SkyWay developer's dashboard.
Server host. Defaults to skyway.io
.
Server port. Defaults to 443
.
The path where your self-hosted PeerServer is running. Defaults to '/'
.
true
if you're using SSL. Defaults to true
since skyway.io uses SSL.
true
if you're using SkyWay's TURN server. Defaults to true
. You must apply here to use this feature.
Configuration IceConfig
Array. .Defaults to { 'iceServers': [{ 'url': 'stun:stun.skyway.io:3478' }] }. It is not necessary to set iceServers if you're using SkyWay's TURN server.
Prints log messages depending on the debug level passed in. Defaults to DEBUG_LEVEL_NO_LOGS
.
Prints no logs.
Prints only errors.
Prints errors and warnings.
Prints all logs.
Specify STUN/TURN server settings.
The STUN/TURN server url.
Use when a user name is required.
Use when a password is required.
Specify options for connecting to peers.
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 withdataConnection.metadata
The data serialization format. Default is BINARY. This value changes what type of data can be sent using dataConnection.send
. The value can be obtained from dataConnection.serialization
.
Set serialization type:binary
Set serialization type:binary-utf8
Set serialization type:json
Set serialization type:none
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
Specify options for calling peers.
Any type of metadata associated with the connection, passed in by whoever initiated the connection.
Obtained when an ”error” event occurs. If the OS gives error info, it can be found in the error property.
Enumerated error types.
No error has occurred.
The client 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.
Network error between signalling server.
Error about WebRTC.
error message
Error information object from OS.
Wraps WebRTC's DataChannel. To get one, use Peer connect
or listen for the CONNECTION
event.
Sends data to the remote peer. The processing method changes depending on the serialization
property. Depending on the value of serialization, the data that can be sent between each of the platforms (JavaScript, iOS, and Android) changes. See this chart for details.
The data to send.
Closes the data connection gracefully, cleaning up underlying DataChannels and PeerConnections.
Set event callback for DataConnection.
The number of messages queued to be sent once the browser buffer is no longer full.
A reference to the DataChannel object associated with the connection.
A unique label by which you want to identify this data connection. If left unspecified, a label will be generated at random.
Any type of metadata associated with the connection, passed in by whoever initiated the connection.
Is true
if the connection is open and ready for reading and writing.
The PeerConnection object tied to the connection.
The ID of the peer on the other end of this connection.
Whether the underlying data channels should be reliable. Is set when the connection is opened.
The serialization format to use when sending data. Is set when the connection is opened.
For data connections, this is always 'data'
.
Wraps WebRTC's media streams. Obtained from Peer.call
or the CALL
event.
Answer media connections obtained from a call
event. You can set your own media stream as the parameter.
MediaStream
obtained from Navigator.getUserMedia.
Closes the media connection.
Set listeners for MediaEventEnum event.
Is true
if the connection is open and ready for reading and writing.
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'
.
close MediaStream.
Gets the number of VideoTracks added to the MediaStream.
Sets the play state of VideoTracks in a MediaStream.
Gets the play state of the VideoTrack.
The index of the VideoTrack. VideoTrack indexes are 0 or greater.
The number of Audio tracks added to media stream.
Set the play state of audio track added to media stream.
Get audio track play state.
The index of the AudioTrack. AudioTrack indexes are 0 or greater.
Change camera if possible while using the local media stream.Returns true
if it successfully changes camera, false
otherwise.
The object to display the video.
Add mediastream and Track No, as a media source to the canvas.
mediastream to add.
The index of the VideoTrack. VideoTrack indexes are 0 or greater.
Remove mediastream and Track No, as a media source from the canvas.
mediastream to remove.
The index of the VideoTrack. VideoTrack indexes are 0 or greater.
Options for the Navigator.getUserMedia function.
Set the video. true
enable the video, false
disable the video. Defaults to true
.
Set the audio. true
enable the audio, false
disable the audio. Defaults to true
.
Set camera. Defaults to FRONT.
Use camera found first.The order depends on system.
Use camera outside. If it's not found, use camera found first.
Use camera inside. If it's not found, use camera found first.
Set the width pixel maximum limit. If you set 0
, it depends on WebRTC engine. Defaults to 640
.
Set the width pixel minimum limit. If you set 0
, it depends on WebRTC engine. Defaults to 0
.
Set the height pixel maximum limit. If you set 0
, it depends on WebRTC engine. Defaults to 640
.
Set the height pixel minimum limit. If you set 0
, it depends on WebRTC engine. Defaults to 0
.
Set the frame rate maximum limit. If you set 0
, it depends on WebRTC engine. Defaults to 10
.
Set the frame rate minimum limit. If you set 0
, it depends on WebRTC engine. Defaults to 0
.