Deprecated!

We have released a new WebRTC platform, ECLWebRTC, to take the place of SkyWay. We will be shutting down the SkyWay servers in March 2018. Customers who are currently using SkyWay are required to migrate to ECLWebRTC by then. Click here for the ECLWebRTC API reference.

×

PeerJS docsSkyWay Version


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.

Setup

1. Include the Javascript client

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.

2. Create the Peer object

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!

Usage

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.

Data connections

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.

Start connection
Receive connection
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.

Video/audio calls

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.

Start call
Answer 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);
});

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.

SkyWay Rest API

listAllPeers()

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.

Common questions

What kind of data can I send?

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.

Are there any caveats?

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.

How do I use a TURN server?

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.

What is the current state of browser compatibility?

We keep an frequently-updated catalogue of WebRTC compatibility information and caveats here.

What if my peer has not yet connected to the server when I attempt to connect to it?

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.

Why am I unable to connect?

You could be behind a symmetric NAT, in which case you'll need to set up a TURN server.

What about latency/bandwidth?

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.

More questions?

Discuss SkyWay on SkyWay Technical Forum Google Group.

Discuss PeerJS on PeerJS Google Group.

Disclaimer

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.

API Reference«»

Getting Started

Peerconstructorvar peer = new Peer([id], [options]);

A peer can connect to other peers and listen for connections.

[id]string

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.

[options]object
keystring

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.

hoststring

Server host. Defaults to skyway.io. Also accepts '/' to signify relative hostname.

portnumber

Server port. Defaults to 443.

securebooleanbeta (0.3.0)

true if you're using SSL. Defaults to true since skyway.io uses SSL.

turnbooleanskyway

true if you're using SkyWay's TURN server. Defaults to true. You must apply here to use this feature.

configobject

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.

debugnumberbeta (0.3.0)

Prints log messages depending on the debug level passed in. Defaults to 0.

0

Prints no logs.

1

Prints only errors.

2

Prints errors and warnings.

3

Prints all logs.

peer.connectmethodvar dataConnection = peer.connect(id, [options]);

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.

idstring

The brokering ID of the remote peer (their peer.id).

[options]object
labelstring

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

Metadata associated with the connection, passed in by whoever initiated the connection. Can be accessed with dataConnection.metadata. Can be any serializable type.

serializationstring

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.

reliableboolean

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.

peer.callmethodbeta (0.3.0)var mediaConnection = peer.call(id, stream);

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.

idstring

The brokering ID of the remote peer (their peer.id).

streamMediaStream

Something else

peer.onmethodpeer.on(event, callback);

Set listeners for peer events.

'open'eventpeer.on('open', function(id) { ... });

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.

'connection'eventpeer.on('connection', function(dataConnection) { ... });

Emitted when a new data connection is established from a remote peer.

'call'eventbeta (0.3.0)peer.on('call', function(mediaConnection) { ... });

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.

'close'eventpeer.on('close', function() { ... });

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.

'error'eventpeer.on('error', function(err) { ... });

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:

'browser-incompatible'Errorfatal

The client's browser does not support some or all WebRTC features that you are trying to use.

'invalid-id'Errorfatal

The ID passed into the Peer constructor contains illegal characters.

'invalid-key'Errorfatal

The API key passed into the Peer constructor contains illegal characters or is not in the system (cloud server only).

'unavailable-id'Errorfatal

The ID passed into the Peer constructor is already taken.

'ssl-unavailable'Errorfatal

PeerJS is being used securely, but the server does not support SSL.

'server-disconnected'Error

You've already disconnected this peer and can no longer make any new connections on it.

'server-error'Errorfatal

Unable to reach the server.

'socket-error'Errorfatal

An error from the underlying socket.

'socket-closed'Errorfatal

The underlying socket closed unexpectedly.

peer.disconnectmethodpeer.disconnect();

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.

peer.destroymethodpeer.destroy();

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.

peer.listAllPeersmethodskywaypeer.listAllPeers(function(list) { ... });

Get an array of PeerIDs of users connected with the same API key.

peer.idstring

The brokering ID of this peer. If no ID was specified in the constructor, this will be undefined until the open event is emitted.

peer.connectionsobject

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.

peer.disconnectedboolean

false if there is an active connection to the PeerServer.

peer.destroyedboolean

true if this peer and all of its connections can no longer be used.

DataConnectionclass

Wraps WebRTC's DataChannel. To get one, use peer.connect or listen for the connect event.

.sendmethoddataConnection.send(data);

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.

data

The data to send.

.closemethoddataConnection.close();

Closes the data connection gracefully, cleaning up underlying DataChannels and PeerConnections.

.onmethoddataConnection.on(event, callback);

Set listeners for data connection events.

'data'eventdataConnection.on('data', function(data) { ... });

Emitted when data is received from the remote peer.

'open'eventdataConnection.on('open', function() { ... });

Emitted when the connection is established and ready-to-use.

'close'eventdataConnection.on('close', function() { ... });

Emitted when either you or the remote peer closes the data connection.Firefox does not yet support this event.

'error'eventdataConnection.on('error', function(err) { ... });
.dataChannelobject

A reference to the RTCDataChannel object associated with the connection.

.labelstring

The optional label passed in or assigned by PeerJS when the connection was initiated.

.metadata

Any type of metadata associated with the connection, passed in by whoever initiated the connection.

.serializationstring

The serialization format of the data sent over the connection. Can be binary (default), binary-utf8, json, or none.

.openboolean

This is true if the connection is open and ready for read/write.

.peerstring

The ID of the peer on the other end of this connection.

.typestring

For data connections, this is always 'data'.

.bufferSizenumber

The number of messages queued to be sent once the browser buffer is no longer full.

MediaConnectionclassbeta (0.3.0)

Wraps WebRTC's media streams. To get one, use peer.call or listen for the call event.

.answermethodmediaConnection.answer([stream]);

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.

[stream]MediaStream

A WebRTC media stream from getUserMedia.

.closemethodmediaConnection.close();

Closes the media connection.

.onmethodmediaConnection.on(event, callback);

Set listeners for media connection events.

'stream'eventmediaConnection.on('stream', function(stream) { ... });

Emitted when a remote peer adds a stream.

'close'eventmediaConnection.on('close', function() { ... });

Emitted when either you or the remote peer closes the media connection.Firefox does not yet support this event.

'error'eventmediaConnection.on('error', function(err) { ... });
.openboolean

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.

.metadata

Any type of metadata associated with the connection, passed in by whoever initiated the connection.

.peerstring

The ID of the peer on the other end of this connection.

.typestring

For media connections, this is always 'media'.

utilobjectutility

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.'

.browserstringif (util.browser === 'Firefox') { /* OK to peer with Firefox peers. */ }

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).

.supportsobjectif (util.supports.data) { /* OK to start a data connection. */ }

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.

.audioVideoboolean

True if the current browser supports media streams and PeerConnection.

.databoolean

True if the current browser supports DataChannel and PeerConnection.

.binaryboolean

True if the current browser supports binary DataChannels.

.reliableboolean

True if the current browser supports reliable DataChannels.

SkyWay iOS SDK docs


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

Setup

1. Add required libraries and frameworks

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

2. Import SkyWay iOS SDK

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.

3. Create the SKWPeer object

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!

Usage

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.

Data connections

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.

Start connection
SKWDataConnection* dataConnection = [peer connectWithId:'dest-peer-id'];
Receive connection
[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.

Video/audio calls

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.

Start call
SKWMediaConnection* mediaConnection = [peer callWithId:dest-peer-id stream:mediaStream];
Answer call
[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.

SkyWay RestAPI

listAllPeers

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.

FAQ

What kind of data can I send?

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.

Are there any caveats?

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.

How do I use a TURN server?

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.

What if my peer has not yet connected to the server when I attempt to connect to it?

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.

Why am I unable to connect?

You could be behind a symmetric NAT, in which case you'll need to set up a TURN server.

What about latency/bandwidth?

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.

Supported OS

iOS 7+

Supported devices

iPhone 5+、iPodTouch 6+、iPad 2+

More questions?

Discuss SkyWay on SkyWay Technical Forum Google Group.

Disclaimer

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.

API Reference«»

Getting Started

SKWPeerCLASSSKWPeer* peer = [[SKWPeer alloc] initWithId:peerId options:options];
SKWPeer* peer = [[SKWPeer alloc] initWithOptions:options];

A peer can connect to other peers and listen for connections.

[peerId]NSString

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.

optionsSKWPeerOption

The options object.

connectWithIdMETHODSKWDataConnection* dataConnection = [peer connectWithId:peerId];
SKWDataConnection* dataConnection = [peer connectWithId:peerId options:options];

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.

peerIdNSString

The brokering ID of the remote peer (their identity)

[options]SKWConnectOption

The options object.

callWithIdSKWMediaConnection* mediaConnection = [peer callWithId:peerId stream:stream];
SKWMediaConnection* mediaConnection = [peer callWithId:peerId stream:stream options:options];

Calls the remote peer specified by idで and returns a SKWMediaConnection.Be sure to listen on the error event in case the connection fails.

peerIdNSString

The brokering ID of the remote peer (theiridentity).

streamSKWMediaStream

The caller's media stream

[options]SKWCallOption

The options object.

onMETHOD[peer on:event callback:^(NSObject* obj)callback];

Set listeners for SKWPeerEvent.

eventSKWPeerEventEnum

Specifies the event type.

SKW_PEER_EVENT_OPEN[peer on:SKW_PEER_EVENT_OPEN callback:^(NSObject* ownId){ ... }];

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.

SKW_PEER_EVENT_CONNECTION[peer on:SKW_PEER_EVENT_CONNECTION callback:^(NSObject* dataConnection){ ... }];

Emitted when a new data connection is established from a remote peer. The callback function parameter is an SKWDataConnection object.

SKW_PEER_EVENT_CALL[peer on:SKW_PEER_EVENT_CALL callback:^(NSObject* mediaConnection){ ... }];

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.

SKW_PEER_EVENT_CLOSE[peer on:SKW_PEER_EVENT_CLOSE callback:^(NSObject* obj){ ... }];

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.

SKW_PEER_EVENT_DISCONNECTED[peer on:SKW_PEER_EVENT_DISCONNECTED callback:^(NSObject* obj){ ... }];

Emitted when the peer isdisconnected from the signalling server.

SKW_PEER_EVENT_ERROR[peer on:SKW_PEER_EVENT_ERROR callback:^(NSObject* obj){ ... }];

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.

callback

Specifies the Block to call when the event is triggered.

disconnectMETHOD[peer disconnect];

Close the connection to the server, leaving all existing data and media connections intact.disconnectedwill 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.

reconnectMETHOD[peer reconnect];

Reconnects to the signaling server. Connects using the same peerID. Only succeeds if disconnected using disconnect. Will not work if disconnected using destroy.

destroyMETHOD[peer 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.

listAllPeersMETHOD[peer listAllPeers:^(NSArray* aryPeers){ ... }];

Get an NSArray of PeerIDs of users connected with the same API key.

identityNSString

The brokering ID of this peer. If no ID was specified in the SKWPeer class, this will be undefined until theopen event is emitted.

connectionsNSMutableDictionary

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.

isDisconnectedBOOL

NO if there is an active connection to the PeerServer.

isDestroyedBOOL

YES if this peer and all of its connections can no longer be used.

SKWPeerOptionCLASSSKWPeerOption* options = [[SKWPeerOption alloc] init];

Specify connection settings.

keyNSString

API key for the cloud PeerServer.

domainNSString

The domain registered with the API key on the SkyWay developer's dashboard.

[host]NSString

Server host. Defaults to skyway.io.

[port]NSInteger

Server port. Defaults to 443.

[path]NSString

The path where your self-hosted PeerServer is running. Defaults to '/'.

[secure]BOOL

YES if you're using SSL. Defaults to YES since skyway.io uses SSL.

[turn]BOOL

YES if you're using SkyWay's TURN server. Defaults to YES. You must apply here to use this feature.

[config]NSArray

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.

[debug]SKWDebugLevelEnum

Prints log messages depending on the debug level passed in. Defaults to SKW_DEBUG_LEVEL_NO_LOGS.

SKW_DEBUG_LEVEL_ONLY_ERROR

Prints only errors.

SKW_DEBUG_LEVEL_ERROR_AND_WARNING

Prints errors and warnings.

SKW_DEBUG_LEVEL_ALL_LOGS

Prints all logs.

SKWIceConfigCLASSSKWIceConfig* config = [[SKWIceConfig alloc] init];

Specify STUN/TURN server settings.

urlNSString

The STUN/TURN server url.

[username]NSString

Use when a user name is required.

[credential]NSString

Use when a password is required.

SKWConnectOptionCLASSSKWConnectOption* options = [[SKWConnectOption alloc] init];

Specify options for connecting to peers.

labelNSString

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

metadataNSString

Metadata associated with the connection, passed in by whoever initiated the connection. Can be accessed withdataConnection.metadata.

serializationSKWSerializationEnum

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.

SKW_SERIALIZATION_BINARY

Set serialization type:binary

SKW_SERIALIZATION_BINARY_UTF8

Set serialization type:binary-utf8

SKW_SERIALIZATION_JSON

Set serialization type:json

SKW_SERIALIZATION_NONE

Set serialization type:none

reliableBOOL

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

SKWCallOptionCLASSSKWCallOption* options = [[SKWCallOption alloc] init];

Specify options for calling peers.

metadataNSString

Any type of metadata associated with the connection, passed in by whoever initiated the connection.

SKWPeerErrorCLASS

Obtained when an ”error” event occurs. If the OS gives error info, it can be found in the error property.

typeSKWPeerErrorEnum

Enumerated error types.

SKW_PEER_ERR_NO_ERRORErrorfatal

No error has occurred

SKW_PEER_ERR_BROWSER_INCOMPATIBLEErrorfatal

The client does not support some or all WebRTC features that you are trying to use.

SKW_PEER_ERR_INVALID_IDErrorfatal

The ID passed into the SKWPeer constructor contains illegal characters.

SKW_PEER_ERR_INVALID_KEYErrorfatal

The API key passed into the SKWPeer constructor contains illegal characters or is not in the system (cloud server only).。

SKW_PEER_ERR_UNAVAILABLE_IDErrorfatal

The ID passed into the SKWPeer constructor is already taken.

SKW_PEER_ERR_SSL_UNAVAILABLEErrorfatal

The server does not support SSL.

SKW_PEER_ERR_DISCONNECTEDError

You've already disconnected this peer and can no longer make any new connections on it.

SKW_PEER_ERR_SERVER_ERRORErrorfatal

Unable to reach the server.

SKW_PEER_ERR_SOCKET_ERRORErrorfatal

An error from the underlying socket.

SKW_PEER_ERR_SOCKET_CLOSEDErrorfatal

The underlying socket closed unexpectedly.

SKW_PEER_ERR_NETWORKErrorfatal

Network error between signalling server.

SKW_PEER_ERR_PEER_UNAVAILABLEErrorfatal

The Peer is unavailable.

SKW_PEER_ERR_WEBRTCErrorfatal

Error about WebRTC.

messageNSString

error message

errorNSError

Error information object from OS.

SKWDataConnectionCLASS

Wraps WebRTC's DataChannel. To get one, use SKWPeer connectWithId or listen for the SKW_PEER_EVENT_CONNECTION event.

sendMETHODBOOL bResult = [dataConnection send:data];

Sends data to the remote peer. The processing method changes depending on the serializationproperty. 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.

data

The data to send.

closeMETHOD[dataConnection close];

Closes the data connection gracefully, cleaning up underlying DataChannels and PeerConnections.

onMETHOD[dataConnection on:event callback:^(NSObject* obj)callback];

Set event callback for SKWDataConnection events.

eventSKWDataConnectionEventEnum

Data connection event types.

SKW_DATACONNECTION_EVENT_DATA[dataConnection on:SKW_DATACONNECTION_EVENT_DATA callback:^(NSObject* obj){ ... }];

Emitted when data is received from the remote peer.

SKW_DATACONNECTION_EVENT_OPEN[dataConnection on:SKW_DATACONNECTION_EVENT_OPEN callback:^(NSObject* obj){ ... }];

Emitted when the connection is established and ready-to-use.

SKW_DATACONNECTION_EVENT_CLOSE[dataConnection on:SKW_DATACONNECTION_EVENT_CLOSE callback:^(NSObject* obj){ ... }];

Emitted when either you or the remote peer closes the data connection.

SKW_DATACONNECTION_EVENT_ERROR[dataConnection on:SKW_DATACONNECTION_EVENT_ERROR callback:^(NSObject* obj){ ... }];

The callback function parameter is aSKWPeerError parameter.

callback

Specifies the Block to call when the event is triggered.

bufferSizeNSUInteger

The number of messages queued to be sent once the browser buffer is no longer full.

dataChannelSKWDataChannel

A reference to the SKWDataChannel object associated with the connection.

labelNSString

A unique label by which you want to identify this data connection. If left unspecified, a label will be generated at random.

metadataNSString

Any type of metadata associated with the connection, passed in by whoever initiated the connection.

isOpenBOOL

Is YES if the connection is open and ready for reading and writing.

peerConnectionRTCPeerConnection

The RTCPeerConnection object tied to the connection.

peerNSString

The ID of the peer on the other end of this connection.

reliableBOOL

Whether the underlying data channels should be reliable. Is set when the connection is opened.

serializationSKWSerializationEnum

The serialization format to use when sending data. Is set when the connection is opened.

typeNSString

For data connections, this is always 'data'.

SKWMediaConnectionCLASS

Wraps WebRTC's media streams. Obtained from Peer.callWithId or the SKW_PEER_EVENT_CALL event.

answerMETHOD[mediaConnection answer];
[mediaConnection answer:stream];

Answer media connections obtained from a call event. You can set your own media stream as the parameter.

[stream]SKWMediaStream

SKWMediaStream obtained from SKWNavigator.getUserMedia.

closeMETHOD[media close];

Closes the media connection.

onMETHOD[mediaConnection on:event callback:^(NSObject* obj)callback];

Set listeners for SKWMediaConnectionEnum event.

eventSKWMediaConnectionEnum

MediaConnection event types.

SKW_MEDIACONNECTION_EVENT_STREAM[mediaConnection on:SKW_MEDIACONNECTION_EVENT_STREAM callback:^(NSObject* stream){ ... }];

Emitted when a remote peer adds a stream.

SKW_MEDIACONNECTION_EVENT_CLOSE[mediaConnection on:SKW_MEDIACONNECTION_EVENT_CLOSE callback:^(NSObject* obj){ ... }];

Emitted when either you or the remote peer closes the media connection.

SKW_MEDIACONNECTION_EVENT_ERROR[mediaConnection on:SKW_MEDIACONNECTION_EVENT_ERROR callback:^(NSObject* obj){ ... }];

The class of callback arguments isSKWPeerError.

callback

Specifies the Block to call when the event is triggered.

isOpenBOOL

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.

metadataNSString

Any type of metadata associated with the connection, passed in by whoever initiated the connection.

peerNSString

The ID of the peer on the other end of this connection.

typeNSString

For media connections, this is always 'media'.

SKWMediaStreamCLASS
closeMETHOD[stream close];

close MedisStream.

getVideoTracksMETHODNSUInteger videos = [stream getVideoTracks];

Gets the number of VideoTracks added to the MediaStream.

setEnableVideoTrackMETHOD[stream setEnableVideoTrack:pos enable:enable];

Sets the play state of VideoTracks in a MediaStream.

posNSUInteger

The index of the VideoTrack. VideoTrack indexes are 0 or greater.

enableBOOL

Play if YES, stop if NO.

getEnableVideoTrackMETHODBOOL enable = [stream getEnableVideoTrack:pos];

Gets the play state of the VideoTrack.

posNSUInteger

The index of the VideoTrack. VideoTrack indexes are 0 or greater.

getAudioTracksMETHODNSUInteger audios = [stream getAudioTracks];

The number of Audio tracks added to media stream.

setEnableAudioTrackMETHOD[stream setEnableAudioTrack:pos enable:enable];

Set the play state of audio track added to media stream.

posNSUInteger

The index of the AudioTrack. AudioTrack indexes are 0 or greater.

enableBOOL

Play if YES, stop if NO.

getEnableAudioTrackMETHODBOOL enable = [stream getEnableAudioTrack:pos];

Get audio track play state.

posNSUInteger

The index of the AudioTrack. AudioTrack indexes are 0 or greater.

setCameraPositionMETHODBOOL result = [stream setCameraPosition:pos];

In case of using iOS device's local media stream, set used camera

posSKWCameraPositionEnum

Set used camera position.

SKW_CAMERA_POSITION_UNSPECIFIED

Use camera found first. The order depends on the system.

SKW_CAMERA_POSITION_BACK

Use back camera.

SKW_CAMERA_POSITION_FRONT

Use front camera.

getCameraPositionMETHODSKWCameraPositionEnum pos = [stream getCameraPosition];

In case of using iOS device's local media stream, get used camera

posSKWCameraPositionEnum

Get used camera position.

SKW_CAMERA_POSITION_UNSPECIFIED

Camera position is unspecified.

SKW_CAMERA_POSITION_BACK

Camera position is back.

SKW_CAMERA_POSITION_FRONT

Camera position is front.

switchCameraMETHODBool result = [stream switchCamera];

Change camera if possible while using iOS device's local media stream. Returns true if it successfully changes camera, false otherwise.

SKWVideoOBJECTSKWVideo* video = [[SKWVideo alloc] initWithFrame:(CGRect)rect];

The object to display the video.

addSrcMETHOD[video addSrc:stream track:trackNo];

Add mediastream and Track No, as a media source to the SKWVideo object.

streamSKWMediaStream

mediastream to add.

trackNoNSUInteger

The index of the VideoTrack. VideoTrack indexes are 0 or greater.

removeSrcMETHOD[video removeSrc:stream track:trackNo];

Remove mediastream and Track No, as a media source from the SKWVideo object.

streamSKWMediaStream

mediastream to remove.

trackNoNSUInteger

The index of the VideoTrack. VideoTrack indexes are 0 or greater.

setDidChangeVideoSizeCallbackMETHOD[video setDidChangeVideoSizeCallback:^(CGSize size)callback

Callback called when video size changes.

callback

Specifies the Block to call when the event is triggered.

SKWNavigatorCLASS

Class to get Video.

initializeMETHOD[SKWNavigator initialize:peer];

Initialize Navigator

peerSKWPeer

Initialized SKWPeer object

terminateMETHOD[SKWNavigator terminate];

Terminate navigator

getUserMediaMETHODSKWMediaStream* stream = [SKWNavigator getUserMedia:constraints];

Get Local Media Stream.

constraintsSKWMediaConstraints

Media Stream setting

SKWMediaConstraintsCLASS

Options for the SKWNavigator.getUserMedia.

videoFlagBOOL

Set the video. YES enable the video, NO disable the video. Defaults to YES.

audioFlagBOOL

Sets the audio. YES enable the audio, NO disable the audio. Defaults to YES.

cameraModeSKWCameraModeEnum

Sets the camera mode. Defaults to SKW_CAMERA_MODE_SWITCHABLE.

SKW_CAMERA_MODE_SWITCHABLE

You can change the camera during the transmission of the media stream.

SKW_CAMERA_MODE_ADJUSTABLE

You can change the width/height property.

cameraPositionSKWCameraPositionEnum

Set camera. Defaults to SKW_CAMERA_POSITION_FRONT. Enable when the cameraMode is SKW_CAMERA_MODE_ADJUSTABLE.

SKW_CAMERA_POSITION_UNSPECIFIED

Use camera found first. The order depends on the system.

SKW_CAMERA_POSITION_BACK

Use back camera. If it's not found, use camera found first.

SKW_CAMERA_POSITION_FRONT

Use front camera. If it's not found, use camera found first.

maxWidthNSUInteger

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

minWidthNSUInteger

Set the width pixel minimum limit. Defaults to 192. Enable when the cameraMode is SKW_CAMERA_MODE_ADJUSTABLE.

maxHeightNSUInteger

Set the height pixel maximum limit. Defaults to 480. Enable when the cameraMode is SKW_CAMERA_MODE_ADJUSTABLE.

minHeightNSUInteger

Set the height pixel minimum limit. Defaults to 144. Enable when the cameraMode is SKW_CAMERA_MODE_ADJUSTABLE.

SkyWay Android SDK docs


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

Setup

1. Add required settings

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" />

2. Import SkyWay Android SDK

Add SkyWay.aar to your application and import class files.

#import io.skyway.Peer.*

3. Create the Peer object

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!

Usage

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.

Data connections

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.

Start connection
DataConnection dataConnection = peer.connect('dest-peer-id');
Receive connection
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.

Video/audio calls

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.

Start call
MediaConnection mediaConnection = peer.call('dest-peer-id',mediaStream);
Answer call
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.

SkyWay RestAPI

listAllPeers

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.

FAQ

What kind of data can I send?

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.

Are there any caveats?

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.

How do I use a TURN server?

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.

What if my peer has not yet connected to the server when I attempt to connect to it?

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.

Why am I unable to connect?

You could be behind a symmetric NAT, in which case you'll need to set up a TURN server.

What about latency/bandwidth?

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.

Supported OS

Android 4.0.3+

Supported devices

Nexus 5 2013、Nexus 6 2015、Xperia Z1 2013、ZenPhone 2014、Galaxy S5

More questions?

Discuss SkyWay on SkyWay Technical Forum Google Group.

Disclaimer

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.

API Reference«»

Getting Started

PeerCLASSPeer peer = new Peer(getApplicationContext(),peerId,options);
Peer peer = new Peer(getApplicationContext(),options);

A peer can connect to other peers and listen for connections.

[peerId]String

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.

optionsPeerOption

The options object.

connectMETHODDataConnection dataConnection = peer.connect(peerId);
DataConnection dataConnection = peer.connect(peerId,options);

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.

peerIdString

The brokering ID of the remote peer (theiridentity)

[options]ConnectOption

The options object.

callMETHODMediaConnection mediaConnection = peer.call(peerId,stream);
MediaConnection mediaConnection = peer.call(peerId,stream,option);

Calls the remote peer specified by id and returns a MediaConnection.Be sure to listen on the error event in case the connection fails.

peerIdString

The brokering ID of the remote peer (theiridentity)

streamMediaStream

The caller's media stream

[option]CallOption

The options object.

onMETHODpeer.on(event,callback);

Set listeners for PeerEvent.

eventPeerEventEnum

Specifies the event type.

OPENpeer.on(Peer.PeerEventEnum.OPEN,new OnCallback(){public void onCallback(Object ownId){...}});

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.

CONNECTIONpeer.on(Peer.PeerEventEnum.CONNECTION,new OnCallback(){public void onCallback(Object object){...}});

Emitted when a new data connection is established from a remote peer. The callback function parameter is a DataConnection object.

CALLpeer.on(Peer.PeerEventEnum.CALL,new OnCallback(){public void onCallback(Object 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.

CLOSEpeer.on(Peer.PeerEventEnum.CLOSE,new OnCallback(){public void onCallback(Object object){...}});

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.

DISCONNECTEDpeer.on(Peer.PeerEventEnum.DISCONNECTED,new OnCallback(){public void onCallback(Object object){...}});

Emitted when the peer isdisconnected from the signalling server.

ERRORpeer.on(Peer.PeerEventEnum.ERROR,new OnCallback(){public void onCallback(Object object){...}});

The callback function parameter is a PeerError object. Errors on the peer are almost always fatal and will destroy the peer. Errors from the underlying socket and PeerConnections are forwarded here.

callback

Specifies the callback function to call when the event is triggered.

disconnectMETHODpeer.disconnect();

Close the connection to the server, leaving all existing data and media connections intact.disconnectedwill 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.

destroyMETHODpeer.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 data and media connections.

listAllPeersMETHODpeer.listAllPeers(new OnCallback(){public void onCallback(Object object){...}});

Get an JSONArray of PeerIDs of users connected with the same API key.

identityString

The brokering ID of this peer. If no ID was specified inPeer class, this will be undefined until theopen event is emitted.

connectionsMap

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.

isDisconnectedBoolean

false if there is an active connection to the PeerServer.

isDestroyedBoolean

true if this peer and all of its connections can no longer be used.

PeerOptionCLASSPeerOption options = new PeerOption();

Specify connection settings.

keyString

API key for the cloud PeerServer.

domainString

The domain registered with the API key on the SkyWay developer's dashboard.

[host]String

Server host. Defaults to skyway.io.

[port]int

Server port. Defaults to 443.

[path]String

The path where your self-hosted PeerServer is running. Defaults to '/'.

[secure]Boolean

true if you're using SSL. Defaults to true since skyway.io uses SSL.

[turn]Boolean

true if you're using SkyWay's TURN server. Defaults to true. You must apply here to use this feature.

[config]ArrayList

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.

[debug]DebugLevelEnum

Prints log messages depending on the debug level passed in. Defaults to DEBUG_LEVEL_NO_LOGS.

NO_LOGS

Prints no logs.

ONLY_ERROR

Prints only errors.

ERROR_AND_WARNING

Prints errors and warnings.

ALL_LOGS

Prints all logs.

IceConfigCLASSIceConfig config = new IceConfig();

Specify STUN/TURN server settings.

urlString

The STUN/TURN server url.

[username]String

Use when a user name is required.

[credential]String

Use when a password is required.

ConnectOptionCLASSConnectOption option = new ConnectOption();

Specify options for connecting to peers.

labelString

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

metadataString

Metadata associated with the connection, passed in by whoever initiated the connection. Can be accessed withdataConnection.metadata

serializationDataConnection.SerializationEnum

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.

BINARY

Set serialization type:binary

BINARY_UTF8

Set serialization type:binary-utf8

JSON

Set serialization type:json

NONE

Set serialization type:none

reliableBoolean

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

CallOptionCLASSCallOption option = new CallOption();

Specify options for calling peers.

metadataString

Any type of metadata associated with the connection, passed in by whoever initiated the connection.

PeerErrorCLASS

Obtained when an ”error” event occurs. If the OS gives error info, it can be found in the error property.

typePeerErrorEnum

Enumerated error types.

NO_ERRORErrorfatal

No error has occurred.

BROWSER_INCOMPATIBLEErrorfatal

The client does not support some or all WebRTC features that you are trying to use.

INVALID_IDErrorfatal

The ID passed into the Peer constructor contains illegal characters.

INVALID_KEYErrorfatal

The API key passed into the Peer constructor contains illegal characters or is not in the system (cloud server only).

UNAVAILABLE_IDErrorfatal

The ID passed into the Peer constructor is already taken.

SSL_UNAVAILABLEErrorfatal

The server does not support SSL.

DISCONNECTEDError

You've already disconnected this peer and can no longer make any new connections on it.

SERVER_ERRORErrorfatal

Unable to reach the server.

SOCKET_ERRORErrorfatal

An error from the underlying socket.

SOCKET_CLOSEDErrorfatal

The underlying socket closed unexpectedly.

NETWORKErrorfatal

Network error between signalling server.

PEER_UNAVAILABLEErrorfatal

The Peer is unavailable

WEBRTCErrorfatal

Error about WebRTC.

messageString

error message

exceptionException

Error information object from OS.

DataConnectionCLASS

Wraps WebRTC's DataChannel. To get one, use Peer connect or listen for the CONNECTION event.

sendMETHODBOOL bResult = dataConnection.send(data);

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.

data

The data to send.

closeMETHODdataConnection.close();

Closes the data connection gracefully, cleaning up underlying DataChannels and PeerConnections.

onMETHODdataConnection.on(event,new OnCallback(){public void onCallback(Object object){}});

Set event callback for DataConnection.

eventDataEventEnum

Data connection event types.

DATA

Emitted when data is received from the remote peer.

OPEN

Emitted when the connection is established and ready-to-use.

CLOSE

Emitted when either you or the remote peer closes the data connection.

ERROR

The callback function parameter is a PeerError object.

callback

Specifies the callback function to call when the event is triggered.

bufferSizeint

The number of messages queued to be sent once the browser buffer is no longer full.

dataChannelDataChannel

A reference to the DataChannel object associated with the connection.

labelString

A unique label by which you want to identify this data connection. If left unspecified, a label will be generated at random.

metadataString

Any type of metadata associated with the connection, passed in by whoever initiated the connection.

isOpenBOOL

Is true if the connection is open and ready for reading and writing.

peerConnectionPeerConnection

The PeerConnection object tied to the connection.

peerString

The ID of the peer on the other end of this connection.

reliableboolean

Whether the underlying data channels should be reliable. Is set when the connection is opened.

serializationSerializationEnum

The serialization format to use when sending data. Is set when the connection is opened.

BINARY

binary

BINARY_UTF8

binary-utf8

JSON

json

NONE

none

typeString

For data connections, this is always 'data'.

MediaConnectionCLASS

Wraps WebRTC's media streams. Obtained from Peer.call or the CALL event.

answerMETHODmediaConnection.answer();
mediaConnection.answer(stream);

Answer media connections obtained from a call event. You can set your own media stream as the parameter.

[stream]MediaStream

MediaStream obtained from Navigator.getUserMedia.

closeMETHODmedia.close();

Closes the media connection.

onMETHODmedia.on(event, new OnCallback(){puclic void onCallback(Object object){}});

Set listeners for MediaEventEnum event.

eventMediaEventEnum

MediaConnection event types.

STREAM

Emitted when a remote peer adds a stream.

CLOSE

Emitted when either you or the remote peer closes the media connection.

ERROR

The class of callback arguments isPeerError.

callback

Specifies the callback function to call when the event is triggered.

isOpenBOOL

Is true if the connection is open and ready for reading and writing.

metadataString

Any type of metadata associated with the connection, passed in by whoever initiated the connection.

peerString

The ID of the peer on the other end of this connection.

typeString

For media connections, this is always 'media'.

MediaStreamCLASS
closeMETHODstream.close();

close MediaStream.

getVideoTracksMETHODint videos = stream.getVideoTracks();

Gets the number of VideoTracks added to the MediaStream.

setEnableVideoTrackMETHODstream.setEnableVideoTrack(pos,enable);

Sets the play state of VideoTracks in a MediaStream.

posint

The index of the VideoTrack. VideoTrack indexes are 0 or greater.

enableBoolean

Play if true, stop false.

getEnableVideoTrackMETHODBoolean enable = stream.getEnableVideoTrack(pos);

Gets the play state of the VideoTrack.

posint

The index of the VideoTrack. VideoTrack indexes are 0 or greater.

getAudioTracksMETHODint audios = stream.getAudioTracks();

The number of Audio tracks added to media stream.

setEnableAudioTrackMETHODstream.setEnableAudioTrack(pos,enable);

Set the play state of audio track added to media stream.

posint

The index of the AudioTrack. AudioTrack indexes are 0 or greater.

enableBoolean

Play if true, stop false.

getEnableAudioTrackMETHODBoolean enable = stream.getEnableAudioTrack(pos);

Get audio track play state.

posint

The index of the AudioTrack. AudioTrack indexes are 0 or greater.

switchCameraMETHODBoolean enable = stream.switchCamera();

Change camera if possible while using the local media stream.Returns true if it successfully changes camera, false otherwise.

CanvasOBJECTCanvas canvas = (Canvas) findViewById(R.id.ownvideo);

The object to display the video.

addSrcMETHODcanvas.addSrc(stream,trackNo);

Add mediastream and Track No, as a media source to the canvas.

streamMediaStream

mediastream to add.

trackNoint

The index of the VideoTrack. VideoTrack indexes are 0 or greater.

removeSrcMETHODcanvas.removeSrc(stream,trackNo);

Remove mediastream and Track No, as a media source from the canvas.

streamMediaStream

mediastream to remove.

trackNoint

The index of the VideoTrack. VideoTrack indexes are 0 or greater.

NavigatorCLASS

Class to get Video.

initializeMETHODNavigator.initialize(peer);

Initialize Navigator

peerPeer

Initialized Peer object

terminateMETHODNavigator.terminate();

Terminate navigator

getUserMediaMETHODMediaStream stream = Navigator.getUserMedia(constraints);

Get Local Media Stream.

constraintsMediaConstraints

Media Stream setting

MediaConstraintsCLASS

Options for the Navigator.getUserMedia function.

videoFlagBoolean

Set the video. true enable the video, false disable the video. Defaults to true.

audioFlagBoolean

Set the audio. true enable the audio, false disable the audio. Defaults to true.

cameraPositionCameraPositionEnum

Set camera. Defaults to FRONT.

UNSPECIFIED

Use camera found first.The order depends on system.

BACK

Use camera outside. If it's not found, use camera found first.

FRONT

Use camera inside. If it's not found, use camera found first.

maxWidthint

Set the width pixel maximum limit. If you set 0, it depends on WebRTC engine. Defaults to 640.

minWidthint

Set the width pixel minimum limit. If you set 0, it depends on WebRTC engine. Defaults to 0.

maxHeightint

Set the height pixel maximum limit. If you set 0, it depends on WebRTC engine. Defaults to 640.

minHeightint

Set the height pixel minimum limit. If you set 0, it depends on WebRTC engine. Defaults to 0.

maxFrameRateint

Set the frame rate maximum limit. If you set 0, it depends on WebRTC engine. Defaults to 10.

minFrameRateint

Set the frame rate minimum limit. If you set 0, it depends on WebRTC engine. Defaults to 0.