OrtcClient

public class OrtcClient

ORTC client used for real-time connections.
CDN with the latest library version: http://messaging-public.realtime.co/js/2.1.0/ortc.js

Snippets

Code

window.onload = function () {
   loadOrtcFactory(IbtRealTimeSJType, function (factory, error) {
       if (error != null) {
           alert("Factory error: " + error.message);
       } else {
           if (factory != null) {
               // Create ORTC client
               var ortcClient = factory.createClient();
               
               // Set ORTC client properties
               ortcClient.setId('clientId');
               ortcClient.setConnectionMetadata('clientConnMeta');
               ortcClient.setClusterUrl('http://ortc-developers.realtime.co/server/2.1/');
               
               ortcClient.onConnected = function (ortc) {
				          // Connected
                   
                  ortcClient.subscribe('channel1', true, function (ortc, channel, message) {                        
                       console.log("Received message: " + message + " at channel " + channel);                       
                  });                                    

                  ortcClient.subscribeWithBuffer('channel2', 'MyUniqueSubscriberId', function (ortc, channel, seqId, message) {                        
                       console.log("Received message: " + message + " at channel " + channel + " with unique message id " + seqId);                       
                  });
               };
			    
               ortcClient.onDisconnected = function (ortc) { 
				          // Disconnected
               };
               
               ortcClient.onSubscribed = function (ortc, channel) { 
                   // Subscribed to the channel 'channel'
                     
                   ortcClient.send(channel, 'Message to the channel');

                   vat ttl = 0; // Maximum allowed
                   ortcClient.publish(channel, 'Message to the channel with guaranteed delivery', ttl, 
                    function(err, seqId) {
                      if(err) {
                        console.log("Error publishing message:", err);
                      } else {
                        console.log("Message published with unique message id:", seqId);
                      }
                  });
               };
                                           
    			    ortcClient.onException = function (ortc, exception) {
    				    // Exception occurred: 'exception'
                   };
                   
    			    ortcClient.onReconnecting = function (ortc) {
    				    // Trying to reconnect
                   };
                   
    			    ortcClient.onReconnected = function (ortc) {
    				    // Reconnected
                   };
                   
    			    ortcClient.connect('myApplicationKey', 'myAuthenticationToken');
                }
        }
    }); 
};

Constructors

object OrtcClient()

Creates a new instance of the ORTC Client class.

Code

var ortcClient = factory.createClient();

Functions

void connect(string applicationKey, string authenticationToken)

Connects the client using the supplied application key and authentication token.

Parameters

string applicationKey

The application key.

string authenticationToken

The authentication token.

Code

ortcClient.connect('myApplicationKey', 'myAuthenticationToken');

void disconnect()

Disconnects the client.

Code

ortcClient.disconnect();

string getAnnouncementSubChannel()

Gets the client announcement subchannel.

string getClusterUrl()

Gets the cluster server URL.

string getConnectionMetadata()

Gets the client connection metadata.

int getConnectionTimeout()

Gets the connection timeout.

boolean getHeartbeatActive()

Get heartbeat active value.

int getHeartbeatFails()

Get how many times can the client fail the heartbeat.

int getHeartbeatTime()

Get heartbeat interval.

string getId()

Gets the client identifier.

string getProtocol()

Gets the client connection protocol.

string getSessionId()

Gets the client session identifier.

string getUrl()

Gets the server URL.

boolean getIsConnected()

Indicates whether the client is connected.

boolean isSubscribed(string channel)

Indicates whether the client is subscribed to the supplied channel.

Parameters

string channel

The channel name.

Code

var isSubscribed = ortcClient.isSubscribed('channel1');

void presence(object Object, function Callback)

Gets a json indicating the subscriptions in the specified channel and if active the first 100 unique metadata.

Parameters

object Object

literal with presence attributes.

Properties

String applicationKey

Application key with access to presence service (optional if connected).

String authenticationToken

Authentication token with access to presence service (optional if connected).

String channel

Channel with presence data active.

boolean isCluster

Specifies if url is cluster (optional if connected).

String url

Server containing the presence service (optional if connected).

function Callback

with error and result parameters.

Code

if (ortcClient.getIsConnected()) {
    presenceData = {
        channel: channel
    };
} else {
    var presenceData = {
        applicationKey: appKey,
        authenticationToken: authToken,
        isCluster: isCluster,
        url: url,
        channel: channel
    };
}

ortcClient.presence(presenceData,
function (error, result) {
    if (error) {
        console.log('Presence error: ' + error);
    } else {
        if (result) {
            for (var metadata in result.metadata) {
                console.log(' ' + metadata + ' : ' + result.metadata[metadata]);
            }

            console.log('Subscriptions on channel ' + channel + ' : ' + result.subscriptions);
        } else {
            console.log('Subscriptions on channel ' + channel + ' : ' + 0);
        }
    }
});

void send(string channel, string message)

Sends the supplied message to the supplied channel.

Parameters

string channel

The channel name.

string message

The message to send.

Code

ortcClient.send('channel1', 'This message goes to channel1');

void publish(string channel, string message, integer ttl, function(err, seqId) result)

Publishes the supplied message to the supplied channel using guaranteed delivery mode.

Parameters

string channel

The channel name.

string message

The message to send.

integer ttl

The maximum amount of time (in seconds) the message is kept in the delivery buffer before it expires. To use the maximum allowed by the server use 0 as TTL.

function(err, seqId) result

Callback with the publish result. If an error ocourred err will contain the error description otherwise seqId will contain the published message unique message id.

Code

var ttl = 5 * 60; // 5 minutes
ortcClient.publish("MyChannel", "My message", ttl, function(err, seqId) {
    if(err) {
        console.log("ERROR PUBLISHING: " + err);
    } else {
        console.log("PUBLISHED WITH UNIQUE ID: " + seqId);
    }
});
    

void setAnnouncementSubChannel(string channel)

Sets the client announcement subchannel.

Parameters

string channel

The client announcement subchannel.

void setClusterUrl(string clusterUrl)

Sets the cluster server URL.

Parameters

string clusterUrl

The cluster server URL.

void setConnectionMetadata(string connectionMetadata)

Sets the client connection metadata.

Parameters

string connectionMetadata

The client connection metadata.

void setConnectionTimeout(int connectionTimeout)

Sets the connection timeout.

Parameters

int connectionTimeout

The connection timeout.

void setHeartbeatActive(boolean active)

Set heartbeat active. Heartbeat provides better accuracy for presence data.

Parameters

boolean active

Heartbeat active value.

void setHeartbeatFails(int newHeartbeatFails)

Set heartbeat fails. Defines how many times can the client fail the heartbeat.

Parameters

int newHeartbeatFails

The heartbeat fails.

void setHeartbeatTime(int newHeartbeatTime)

Set heartbeat interval.

Parameters

int newHeartbeatTime

The heartbeat interval.

void setId(string id)

Sets the client identifier.

Parameters

string id

The client identifier.

void setProtocol(string protocol)

Sets the client connection protocol.

Parameters

string protocol

The client connection protocol.

void setUrl(string url)

Sets the server URL.

Parameters

string url

The server URL.

void subscribe(string channel, boolean subscribeOnReconnected, function(ortc, channel, message) onMessage)

Subscribes to the supplied channel to receive messages sent to it.

Parameters

string channel

The channel name.

boolean subscribeOnReconnected

Indicates whether the client should subscribe to the channel when reconnected (if it was previously subscribed when connected).

function(ortc, channel, message) onMessage

The callback called when a message arrives at the channel.

Code

ortcClient.subscribe('channel1', true, function (ortc, channel, message) {
	...
});

void subscribeWithFilter(string channel, boolean subscribeOnReconnected, string filter, function(ortc, channel, filtered, message) onMessageWithFilter)

Subscribes to the supplied channel to receive messages sent to it that validate the given filter.

Parameters

string channel

The channel name.

boolean subscribeOnReconnected

Indicates whether the client should subscribe to the channel when reconnected (if it was previously subscribed when connected).

string filter

The filter condition

function(ortc, channel, filtered, message) onMessageWithFilter

The callback called when a message arrives at the channel.
If the filtered parameter is true it means the server was able to filter the message, otherwise the message was not filtered and should be validated by the client.

Code

ortcClient.subscribeWithFilter('channel1', true, 'message.temperature > 70', function (ortc, channel, filtered, message) {
  if(filtered) {
    console.log("Received a filtered message:", message);
  }
});

void subscribeWithBuffer(string channel, string subscriberId, function(ortc, channel, seqId, message) onMessage)

Subscribes to the supplied channel to receive messages sent to it, using a server buffer to guarantee message delivery.

Parameters

string channel

The channel name.

string subscriberId

Identifies uniquely the subscriber, so the server can keep track of the messages already delivered.

function(ortc, channel, seqId, message) onMessage

The callback called when a message is received on the channel. The seqId parameter contains the message unique id.

Code

ortcClient.subscribeWithBuffer('channel1', 'UniqueSubscriberId', function (ortc, channel, seqId, message) {
  ...
});

void subscribeWithOptions(Object options, function(ortc, msgOptions) onMessage)

Subscribes to the supplied channel to receive messages sent to it, using a set of options to allow the mix of different subscription features like buffer, filter and push notifications.

Parameters

Object options

The subscription options containing the following properties: channel, subscribeOnReconnected, filter and subscriberId

function(ortc, msgOptions) onMessage

The callback called when a message is received on the channel. The msgOptions parameter contains an object with the following properties: channel, seqId, filtered and message.

Code

  var options = {
      channel: "MyChannel", 
      subscribeOnReconnected: true,  
      filter: "message.temperature > 70", 
      subscriberId: "MyUniqueSubscriberId"
  }

  ortcClient.subscribeWithOptions(options, function (ortc, msgOptions) {
    var channel = msgOptions.channel;
    var seqId = msgOptions.seqId;
    var filtered = msgOptions.filtered;
    var message = msgOptions.message;

    console.log("Received message", message, "in channel", channel, "with unique id", seqId);
});

void unsubscribe(string channel)

Unsubscribes from the supplied channel to stop receiving messages sent to it.

Parameters

string channel

The channel name.

Code

ortcClient.unsubscribe('channel1');

Events

onConnected(object ortc)

Occurs when the client connects.

Parameters

object ortc

The ORTC Client object.

Code

ortcClient.onConnected = function (ortc) {
	...
};

onDisconnected(object ortc)

Occurs when the client disconnects.

Parameters

object ortc

The ORTC Client object.

Code

ortcClient.onDisconnected = function (ortc) {
	...
};

onException(object ortc, string exception)

Occurs when there is an exception.

Parameters

object ortc

The ORTC Client object.

string exception

The occurred exception.

Code

ortcClient.onException = function (ortc, event) {
	...
};

onReconnected(object ortc)

Occurs when the client reconnects.

Parameters

object ortc

The ORTC Client object.

Code

ortcClient.onReconnected = function (ortc) {
	...
};

onReconnecting(object ortc)

Occurs when the client attempts to reconnect.

Parameters

object ortc

The ORTC Client object.

Code

ortcClient.onReconnecting = function (ortc) {
	...
};

onSubscribed(object ortc, string channel)

Occurs when the client subscribes to a channel.

Parameters

object ortc

The ORTC Client object.

string channel

The channel name.

Code

ortcClient.onSubscribed = function (ortc, channel) {
	...
};

onUnsubscribed(object ortc, string channel)

Occurs when the client unsubscribes from a channel.

Parameters

object ortc

The ORTC Client object.

string channel

The channel name.

Code

ortcClient.onUnsubscribed = function (ortc, channel) {
	...
};