WebSync: Documentation
WebSync clients can publish, subscribe, and receive streaming data, among other things.
They are intended for full client-side integration.
JavaScript Client
Getting Started
Insert the following tag in the <head> section of your page:
<script type="text/javascript" src="http://sync.frozenmountain.com/client.js?v=2.4.3"> </script>
Now you're ready to start coding! Here's a quick sample to get you going:
var client = fm.websync.client; // use your domain key here (if using WebSync On-Demand) client.initialize({ key: '11111111-1111-1111-1111-111111111111' }); client.connect(); client.subscribe({ channel: '/sample/channel', onReceive: function(args) { alert(args.data.text); } }); client.publish({ channel: '/sample/channel', data: { text: 'Hello, world!' } });
Using the Client
Use the JavaScript client by calling the public methods
available in
fm.websync.client. A client will
typically initialize,
connect, and then
subscribe and
publish.
initialize
fm.websync.client.initialize(config);
Initializes the client for use.
config is an object with the following properties:
-
key (string)
Description:WebSync On-Demand Only. The key for your domain.
-
urls (object)
Description:Optional. The proxy a given method should target.Properties:object, with the following properties:
- connect (string)
- The proxy for connect requests to target.
- subscribe (string)
- The proxy for subscribe requests to target.
- publish (string)
- The proxy for publish requests to target.
- unsubscribe (string)
- The proxy for unsubscribe requests to target.
- disconnect (string)
- The proxy for disconnect requests to target.
-
requestTimeout (int, default: 15000)
Description:Optional. The length of time (in ms) to wait for a response before considering a request timed out due to network failure. (Only applies for handshake, subscribe, publish, unsubscribe, and disconnect requests and only in browsers using JSON-P as their transport layer.)
-
backoff (object)
Description:Optional. The retry configuration used by the client when a connection has failed.Properties:object, with the following properties:
- count (int, default: 3)
- The number of reconnect attempts the client will make before invoking the connect method's onFailure handler.
- interval (int, default: 500)
- How quickly (in ms) the first reconnect attempt will be made. Each subsequent attempt will double the backoff interval until the connection has been restablished or count attempts have been made.
-
onUnhandledReceive (function)
Description:Optional, WebSync Server Only.When subscribing clients to channels using the server-side subscribe methods, no client functions are registered to handle the data when it arrives. Instead, this method will be invoked when data arrives.Parameters:object, with the following properties:
- clientId (int)
- The publisher's unique client ID.
- channel (string)
- The channel to which the data was published.
- data (object)
- The published data.
The config object also supports the following optional parameters that affect
how the client connects to WebSync.
-
handlerUrl (string)
Description:Optional. The url of the WebSync Server request handler.
-
streamUrl (string)
Description:Optional. The url for all long-lived connections to use. Like handlerUrl, this url needs to point to the WebSync Server handler, but for maximum performance in older browsers, should be set to a url with a different subdomain.
-
frameUrl (string)
Description:Optional. The url at which the WebSync client iframe can be located. This url must be on the same domain as streamUrl (or handlerUrl if streamUrl is not specified.
Example:
// use your domain key here (if using WebSync On-Demand) fm.websync.client.initialize({ key: '11111111-1111-1111-1111-111111111111', urls: { connect: 'http://mydomain.com/authenticate-proxy.aspx' } });
connect
fm.websync.client.connect(config);
Connects the client to the server and delivers any pending requests.
config is an object with the following properties:
- ext (object)Description:Optional. Extra data to associate with the message (a single serializable object).
- url (string)Description:Optional. The proxy to which the request should be sent.
- onComplete (function)Description:Optional. Callback invoked on success or failure.Parameters:None
-
onSuccess (function)
Description:Optional. Callback invoked if the connect succeeds.Parameters:object, with the following properties:
- clientId (int)
- The unique client ID.
-
onFailure (function)
Description:Optional. Callback invoked if the connect fails.Parameters:object, with the following properties:
- error (string)
- The error message.
Example:
fm.websync.client.connect({
ext: {
foo: 'bar'
},
onComplete: function() {
alert('connect complete');
},
onSuccess: function(args) {
alert('connect win');
},
onFailure: function(args) {
alert('connect fail');
}
});
subscribe
fm.websync.client.subscribe(config);
Subscribes the client to a channel or array of channels. Received messages
are delivered to the onReceive method. (Note that publishers do not receive
their own publications.)
config is an object with the following properties:
-
channel (string or string[])
Description:The name(s) of the channel(s) to subscribe.
- ext (object)Description:Optional. Extra data to associate with the message (a single serializable object).
- url (string)Description:Optional. The proxy to which the request should be sent.
- onComplete (function)Description:Optional. Callback invoked on success or failure.Parameters:None
-
onSuccess (function)
Description:Optional. Callback invoked if the subscribe succeeds.Parameters:object, with the following properties:
- clientId (int)
- The unique client ID.
- channel (string[])
- The channels that were successfully subscribed.
- data (object)
- Additional information relevant to the subscribed channels, such as the
list of currently subscribed client IDs.
e.g. { channels: { '/channel': { clientIds: ['46', '51', '105'] } } }
-
onFailure (function)
Description:Optional. Callback invoked if the subscribe fails.Parameters:object, with the following properties:
- error (string)
- The error message.
-
onReceive (function)
Description:Callback invoked when data is delivered to the channel.Parameters:object, with the following properties:
- clientId (int)
- The publisher's unique client ID.
- channel (string)
- The channel to which the data was published.
- data (object)
- The published data.
-
onMetaReceive (function)
Description:Callback invoked when clients subscribe or unsubscribe to the channel.Parameters:object, with the following properties:
- data (object)
- The event details, including affected client IDs.
e.g. { event: 'subscribe', clientIds: ['123'] }
Example:
fm.websync.client.subscribe({
channel: '/channel/name',
ext: {
foo: 'bar'
},
onComplete: function() {
alert('subscribe complete');
},
onSuccess: function(args) {
alert('subscribe win');
},
onFailure: function(args) {
alert('subscribe fail');
},
onReceive: function(args) {
alert('receive win');
},
onMetaReceive: function(args) {
alert('meta-receive win');
}
});
publish
fm.websync.client.publish(config);
Publishes data to the subscribers of a channel. The data must
be a single serializable object.
config is an object with the following properties:
-
channel (string)
Description:The name of the channel to which the client should publish.
-
data (object)
Description:The data to publish (a single serializable object).
- ext (object)Description:Optional. Extra data to associate with the message (a single serializable object).
- url (string)Description:Optional. The proxy to which the request should be sent.
- onComplete (function)Description:Optional. Callback invoked on success or failure.Parameters:None
-
onSuccess (function)
Description:Optional. Callback invoked if the publish succeeds.Parameters:object, with the following properties:
- clientId (int)
- The unique client ID.
- channel (string)
- The channel to which the data was published.
- data (object)
- The published data.
-
onFailure (function)
Description:Optional. Callback invoked if the publish fails.Parameters:object, with the following properties:
- error (string)
- The error message.
Example:
fm.websync.client.publish({
channel: '/channel/name',
data: {
blah: 'blah',
test: true,
value: 1.2
},
ext: {
foo: 'bar'
},
onComplete: function() {
alert('publish complete');
},
onSuccess: function(args) {
alert('publish win');
},
onFailure: function(args) {
alert('publish fail');
}
});
unsubscribe
fm.websync.client.unsubscribe(config);
Unsubscribes the client from a channel or array of channels.
config is an object with the following properties:
-
channel (string or string[])
Description:The name(s) of the channel(s) to unsubscribe.
- ext (object)Description:Optional. Extra data to associate with the message (a single serializable object).
- url (string)Description:Optional. The proxy to which the request should be sent.
- onComplete (function)Description:Optional. Callback invoked on success or failure.Parameters:None
-
onSuccess (function)
Description:Optional. Callback invoked if the unsubscribe succeeds.Parameters:object, with the following properties:
- clientId (int)
- The unique client ID.
- channel (string[])
- The channels that were successfully unsubscribed.
-
onFailure (function)
Description:Optional. Callback invoked if the unsubscribe fails.Parameters:object, with the following properties:
- error (string)
- The error message.
Example:
fm.websync.client.unsubscribe({
channel: '/channel/name',
ext: {
foo: 'bar'
},
onComplete: function() {
alert('unsubscribe complete');
},
onSuccess: function(args) {
alert('unsubscribe win');
},
onFailure: function(args) {
alert('unsubscribe fail');
}
});
disconnect
fm.websync.client.disconnects(config);
Terminates the connection to the server. A call to connect()
can re-open the connection.
config is an object with the following properties:
- ext (object)Description:Optional. Extra data to associate with the message (a single serializable object).
- url (string)Description:Optional. The proxy to which the request should be sent.
- onComplete (function)Description:Optional. Callback invoked on success or failure.Parameters:None
-
onSuccess (function)
Description:Optional. Callback invoked if the disconnect succeeds.Parameters:object, with the following properties:
- clientId (int)
- The unique client ID.
-
onFailure (function)
Description:Optional. Callback invoked if the disconnect fails.Parameters:object, with the following properties:
- error (string)
- The error message.
Example:
fm.websync.client.disconnect({
ext: {
foo: 'bar'
},
onComplete: function() {
alert('disconnect complete');
},
onSuccess: function(args) {
alert('disconnect win');
},
onFailure: function(args) {
alert('disconnect fail');
}
});
Other Client Methods
The JavaScript client has some additional methods that don't affect
its state, but instead provide useful information for your applications.
getClientId
fm.websync.client.getClientId();
Returns the client's unique identifier, or 0 if it has not connected.
fm.websync.client.getClientId(); // returns client id
Utility Methods
The JavaScript client has some helpful utility methods that can be used
in your own application. They all reside in
fm.websync.utilities.
extend
fm.websync.utilities.extend(dest, src);
Extends destination object by copying all properties from
source object.
var dest = { foo: 'bar', test: true }; var src = { value: 2 test: false }; fm.websync.utilities.extend(dest, src); // dest is now { foo: 'bar', value: 2, test: false }
isArray
fm.websync.utilities.isArray(element);
Detects whether or not an element is an array.
var arr = [ 1, 2, 3 ]; var obj = { foo: 'bar' }; fm.websync.utilities.isArray(arr); // returns true fm.websync.utilities.isArray(obj); // returns false
isString
fm.websync.utilities.isString(element);
Detects whether or not an element is a string.
var arr = [ 1, 2, 3 ]; var obj = { foo: 'bar' }; fm.websync.utilities.isArray("test"); // returns true fm.websync.utilities.isArray({}); // returns false
json.parse
fm.websync.utilities.json.parse(str);
Parses a JSON string into a native JavaScript object.
var str = '{"foo":"bar"}'; var obj = fm.websync.utilities.json.parse(str); // obj is { foo: 'bar' }
json.stringify
fm.websync.utilities.json.stringify(obj);
Serializes a native JavaScript object into a JSON string.
var obj = { foo: 'bar' }; var str = fm.websync.utilities.json.stringify(obj); // str is '{"foo":"bar"}'
log
fm.websync.utilities.log(data, force);
Logs data to the console (or the current document body if console is unavailable).
// use force=true to override global debug value fm.websync.utilities.log('Hello, world', true);
observe
fm.websync.utilities.observe(element, event, handler);
Attaches an event handler to a DOM element.
fm.websync.utilities.observe(window, 'load', function() { alert('Window loaded!'); });
Full Example
A simple demonstration is often the best way to learn.
Put the following code in an HTML file and open it in multiple
browser tabs/windows. Each time a copy loads, it will publish
a simple message to any other loaded pages.
<html> <head> <title>Hello World</title> <script type="text/javascript" src="http://sync.frozenmountain.com/client.js?v=2.4.3"></script> </head> <body> <script type="text/javascript"> var client = fm.websync.client; // initialize the client // use your domain key here (if using WebSync On-Demand) client.initialize({ key: '11111111-1111-1111-1111-111111111111' }); // connect to the server client.connect({ ext: { userName: 'jsmith' } }); // subscribe the client and set up our receive handler client.subscribe({ channel: '/test', onReceive: function(args) { var div = document.createElement('div'); div.innerHTML = args.data.text; document.body.appendChild(div); } }); // publish some data client.publish({ channel: '/test', data: { text: 'Hello, world!' } }); </script> </body> </html>
Using a Proxy
For each client method, the optional
url argument allows you
to redirect the method requests to a different URL. This is known as
"proxying" and allows pre-processing of messages on your server. It is useful for
integrating custom functionality and business logic, such as authentication,
persistence, authorization, contact list management, etc. For more information,
see Proxies.
.NET Client
Getting Started
If you haven't already:
- Download the latest copy of WebSync On-Demand .NET.
- Add a reference to the downloaded library to your project.
You're ready to start using the client!
Using the Client
To create a client, simply instantiate an instance of
Client:
// WebSync On-Demand Only Client client = new Client( "11111111-1111-1111-1111-111111111111", // replace with your domain key "mydomain.com" // replace with your domain name ); // WebSync Server Only Client client = new Client( "http://mydomain.com/request.ashx" // replace with your request handler );
After creating a new client:
-
Attach a method to the
ConnectCompletedevent for post-connect operations. -
Attach a method to the
Receiveevent for receiving incoming messages. -
Call
Connectto kick off the process.
Once the
ConnectCompleted handler has raised, you can make calls
to the other client methods. A typical application will Subscribe
and Publish. Incoming
messages will raise the Receive handler.
All properties and methods are fully documented in the library.
Example
static void Main(string[] args) { // create the client // use your domain key and name here (if using WebSync On-Demand) Client client = new Client( "11111111-1111-1111-1111-111111111111", "mydomain.com" ); // attach the event handlers client.ConnectCompleted += new EventHandler<ConnectCompletedEventArgs>(ConnectCompleted); client.Receive += new EventHandler<ReceiveEventArgs>(Receive); // connect to the server client.Connect(); } void ConnectCompleted(object sender, ConnectCompletedEventArgs e) { // subscribe the client e.Client.Subscribe("/test"); // publish some data e.Client.Publish(new Publication() { Channel = "/test", Data = "{\"text\":\"Hello, world!\"}" // must be valid JSON }); } void Receive(object sender, ReceiveEventArgs e) { // dump the data to the console (in JSON) Console.WriteLine(e.Data); }
Using a Proxy
For each client method, the optional
proxy parameter allows you
to redirect the method requests to a different URL. This is known as
"proxying" and allows custom message pre-processing. It is useful for
integrating custom functionality and business logic, such as authentication,
persistence, authorization, contact list management, etc. For more information,
see Proxies.
