Class Index

Classes


Class StreamHub

The main class for connecting to a StreamHub Push Server and subscribing to topics.

Class Summary
Constructor Attributes Constructor Name and Description
 
Creates a new un-connected StreamHub
Method Summary
Method Attributes Method Name and Description
 
addConnectionListener(oConnectionListener)
Adds a listener to receive connection lost and established events
 
connect(config)
Connects to the server

The page that this call is made from must be under the same domain that you are connecting to.

 
Disconnects from the server
 
publish(sTopic, sJson)
Publishes data on a particular topic.
 
setLogger(oLogger)
Sets the logger for this StreamHub instance
 
subscribe(oTopic, fListener)
Subscribes to a topic or multiple topics
 
unsubscribe(oTopic)
Unsubscribes from a topic or multiple topics
Class Detail
StreamHub()
Creates a new un-connected StreamHub
var hub = new StreamHub();
Method Detail
addConnectionListener(oConnectionListener)
Adds a listener to receive connection lost and established events
// Example - creating and adding a connection listener
var connectionListener = new StreamHub.ConnectionListener();
connectionListener.onConnectionEstablished = function () {
    alert("Connection up");
};
connectionListener.onConnectionLost = function () {
    alert("Connection down");
};
var hub = new StreamHub();
hub.addConnectionListener(connectionListener);
Parameters:
{Object} oConnectionListener
The connection listener to add. It must implement Streamhub.ConnectionListener.
See:
StreamHub.ConnectionListener

connect(config)
Connects to the server

The page that this call is made from must be under the same domain that you are connecting to. For example, assuming you make the call from www.stream-hub.com, the URL must point to a domain under stream-hub.com. The most common idiom is to serve the web content from www.example.com and host the StreamHub server on push.example.com.

// Example - Connecting to a localhost server:
var hub = new StreamHub();
hub.connect("http://localhost:7979/");
// Example - Serving the data from a subdomain
var hub = new StreamHub();
hub.connect("http://push.server.com/");
// Example - Using a cross-domain proxy
var hub = new StreamHub();
hub.connect("http://www.server.com/proxy.php?request=");
// Example - Configuring a single failover server
var hub = new StreamHub();
hub.connect({
    serverList:         ["http://primary.example.com/",
                         "http://backup.example.com/"],
    failoverAlgorithm:  "priority"
});
// Example - Configuring reconnection behaviour
var hub = new StreamHub();
hub.connect({
    serverList:                   ["http://primary.example.com/"],
    initialReconnectDelayMillis:  500,
    maxReconnectDelayMillis:      30000,
    maxReconnectAttempts:         10,       
    useExponentialBackOff:        true,
    backOffMultiplier:            2   
});
// Example - All failover and configuration options
var hub = new StreamHub();
hub.connect({
    serverList:                   ["https://push1.example.com/",
                                   "https://push2.example.com/",
                                   "https://push3.example.com/"],
    failoverAlgorithm:            "random",
    initialReconnectDelayMillis:  1000,
    maxReconnectDelayMillis:      60000,
    maxReconnectAttempts:         -1,       // no maximum
    useExponentialBackOff:        true,
    backOffMultiplier:            2   
});
Parameters:
{String|Object} config
The URL of the server to connect to e.g. http://localhost:7979/ as a string. Or an object specifying detailed configuration options. Note: The trailing slash is required on all URLs.
{String[]} config.serverList Optional
A list of server URLs e.g. ["http://primary.example.com/","http://backup.example.com/"]
{Number} config.initialReconnectDelayMillis Optional, Default: 1000
How long to wait before the first reconnect attempt (in ms)
{Number} config.maxReconnectDelayMillis Optional, Default: -1
The maximum amount of time we ever wait between reconnect attempts (in ms)
{Number} config.maxReconnectAttempts Optional, Default: -1
This is the maximum number of reconnect attempts. A value of -1 indicates there is no maximum.
{Boolean} config.useExponentialBackOff Optional, Default: false
Should an exponential backoff be used between reconnect attempts
{Number} config.backOffMultiplier Optional, Default: 1
The exponent used in the exponential backoff attempts
{String} config.failoverAlgorithm Optional, Default: ordered
The algorithm used to pick a server from the serverList. Either "ordered" for a traversal from the current server in the list to the bottom, "random" for a random pick, or "priority" to always attempt from the top server in the list to the bottom.
{String} config.connectionType Optional, Default: STREAM
The connection type to prefer. Either StreamHub.POLLING_CONNECTION for polling or StreamHub.STREAMING_CONNECTION for streaming.
{String} config.staticUID Optional
Use a static UID instead of a generated one.

disconnect()
Disconnects from the server
hub.disconnect();

publish(sTopic, sJson)
Publishes data on a particular topic. The data contained in sJson will be sent back to the server. The server may choose to publish this data to all subscribed clients or instead return a custom response to this client.
// Example - publishing a chat message
hub.publish("ChatRoom", "{'nickname':'Chatty','message':'Hi room!'}");
// Example - sending a trade
hub.publish("channels.trade", "{'symbol':'GOOG','side':'bid','price':'451.14','amount':'1000'}");
Parameters:
{String} sTopic
The topic to publish the data on
{String} sJson
A string of JSON containing the data to publish

setLogger(oLogger)
Sets the logger for this StreamHub instance
var oLogger = new StreamHub.ElementLogger({elementId : "logMessages"});
hub.setLogger(oLogger);
Parameters:
{Object} oLogger
The logger to set. A logger is required to have one method, called log which takes a String.
See:
StreamHub.ElementLogger

subscribe(oTopic, fListener)
Subscribes to a topic or multiple topics
// Example - subscribing to a single topic
function updateListener(sTopic, oData) {
    // ...
}
hub.subscribe("Topic", updateListener);
// Example - subscribing to multiple topics
function updateListener(sTopic, oData) {
    // ...
}
hub.subscribe(["Topic-1", "Topic-2", "Topic-3"], updateListener);
// Example - reading updates
// Assuming the following data is published in Java code from the server:
Payload payload = new JsonPayload("Topic");
payload.addField("Symbol", "GOOG");
payload.addField("Price", "451.13");
server.publish("Topic", payload);

// The data can be retrieved in JavaScript:
function updateListener(sTopic, oData) {
    alert("Symbol: " + oData['Symbol'] + ", Price: " + oData['Price']);
    // Prints "Symbol: GOOG, Price: 451.13"
}
// Example - enumerating all the fields received in an update
function updateListener(sTopic, oData) {
    var allFields = "";
    for (var p in oData) {
        allFields += "oData[" + p + "] = " + oData[p] + "\n";
    }
    alert("Update received: " + allFields);
}
Parameters:
{String|String[]} oTopic
A single topic as a String or multiple topics as a String array to subscribe to
{Function} fListener
A callback function to receive updates on this topic

unsubscribe(oTopic)
Unsubscribes from a topic or multiple topics
// Example - unsubscribing from a single topic
hub.unsubscribe("Topic");
// Example - unsubscribing from multiple topics
hub.unsubscribe(["Topic-1", "Topic-2", "Topic-3"]);
Parameters:
{String|String[]} oTopic
A single topic as a String or multiple topics as a String array to unsubscribe from

Copyright © 2009 StreamHub. Tutorials, news and guides can be found on the StreamHub Comet Blog.