Skip to content

jQuery.atmosphere.js atmosphere.js API

Jeanfrancois Arcand edited this page Sep 16, 2013 · 8 revisions

The jQuery.atmosphere.js client supports many features. This document describes all the features and how to use them. Using the script is simple and can be summarized as:

  1. Create a Request object
  2. Subscribe
  3. Received Events
  4. Publish Messages

As simple as (use $.atmosphere with if you are using jQuery)

var socket = atmosphere;
var request = new atmosphere.AtmosphereRequest();
var subSocket = socket.subscribe(request);
subSocket.push(data);

atmosphere.js Main Method

The first step when writing a client side application with Atmosphere is to get a reference to the main Atmosphere's client object.

The available methods when doing

var socket = atmosphere;

are

subscribe(AtmosphereRequest)

Subscribe or connect to the remote server. The request's transport will be used. If the transport is not supported by the client or server, the request.fallbackTransport will be used. See this page for the list of supported by browsers and servers. This function returns an AtmosphereRequest (called socket above) that can be used to push messages to the server. For example, if the websocket transport is used, the websocket connection can be reused for pushing messages. For other transport, a new connection will be made every time the socket.push method is used.

publish(AtmosphereRequest)

Publish or push data to the remote server. Depending on the transport used, a new connection will be used or the same connection reused. A new connection will be used when selected transport is polling, long-polling, streaming, jsonp or sse. The same connection will be reused if transport is websocket.

unsubscribe()

Unsubscribe or close the connection.

atmopshere.AtmosphereRequest

var request = new atmosphere.AtmosphereRequest();
request.**{options}**

or

var request = **{options}**

Attributes

url [default = '']

The URL to connect. URL must always starts with http:// or https://

connectTimeout [default = -1]

The connect timeout. If the client fail to connect, the fallbackTransport will be used.

reconnectInterval [default = 5000]

The interval before an attempt to reconnect will be made.

timeout [default = 300000]

The maximum time a connection stay opened when no message (or event) are sent or received.

method [default = 'GET']

The HTTP method to use.

headers [default = {}]

A list of headers to send

contentType [default = '']

The request's content-type

data [default = '']

The request body (required when doing a POST or PUT)

suspend [default = 'true']

Suspend the request, always reconnect if the connection gets closed (for whatever reason), independently of the transport used.

maxRequest [default = '-1']

The maximum number of requests that will be executed. Once the maximum gets reached, the connection will be closed. Default is -1, which means no limit.

maxStreamingLength [default = '10000000']

When the streaming transport is used, the maximum size of the body received. Once reached the connection will be closed and re-opened

logLevel [default = 'info']

The log level. Value allowed are 'info', 'debug' and 'error'

transport [default = 'long-polling']

The transport Atmosphere will use between the client and server. Allowed value are polling, long-polling, streaming, jsonp, sse and websocket

fallbackTransport [default = 'long-polling']

If either the client or server isn't able to support the selected 'transport', the fallback value will be used. Allowed value are polling, long-polling, streaming, jsonp, sse and websocket

fallbackMethod [default = 'GET']

Used when the fallbackTransport gets used.

webSocketImpl [default = null]

The WebSocket API to use. As an example, you can use Flash WebSocket

webSocketUrl [default = null]

The webSocketUrl appended to the request.data when defined. This is useful if the Atmosphere Server Side Component is using a custom implementation of WebSocketProtocol implementation and will be appended to WebSocket messages send to the server. The message will looks like:

data = webSocketPathDelimiter + webSocketUrl + webSocketPathDelimiter + data;

webSocketPathDelimiter [default = '@@]

The token delimiter used to wrap request.data when websockets messages are sent. This value is used with the webSocketUrl attribute.

enableXDR [default = 'false']

Enable CORS Cross Origin Resource Sharing.

rewriteURL [default = 'false']

When enableXDR is set to true, the rewriteURL will be used to decide if the JSESSION_ID cookie be send to the remote server.

attachHeadersAsQueryString [default = 'true']

Pass all headers as query string. Some browser only support the GET method with some transport and prevent setting headers. As an example, the WebSocket API doesn't allow setting headers, and instead the headers will be passed as a query string. See this class for the list of supported headers.

dropAtmosphereHeaders [default = 'true']

By default Atmosphere adds headers like X-Atmosphere-Transport, X-Cache-Date etc. used by the server to track the browser state. The same information is passed as a query string by default (attachHeadersAsQueryString) so if you aren't planning to add any extra headers, set that value to true and instead let the attachHeadersAsQueryString pass the same information. Setting that value to true also facilitate CORS requests handling because no extra headers are added.

executeCallbackBeforeReconnect [default = 'false']

Execute the request's callback before or after reconnecting again to the server.

withCredentials [default = 'false']

True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response.

trackMessageLength [default = 'false']

Track the size of the received request. This attribute must be used with the help of the Atmosphere's Server Side components called TrackMessageSizeFilter. When used, the server will use the following protocol when sending messages back to the client

<message-length><message-delimiter> message <message-delimiter> 

This attribute is useful when your server side component send large chunked message. Using the trackMessageLength, the client will make sure the message has been fully received before invoking the callback. If not set, the callback might be invoked with partial message.

messageDelimiter [default = '|']

The token that delimit the message when the trackMessageLength attribute is used.

shared [default = 'false']

When set to true, Atmospere will share a connection between different browser tabs and windows. Otherwise, a new connection will be established for each tab/window. Also see this example.

enableProtocol [default = true]

When set to true, the atmosphere.js will send extra requests to handshake some data with the server. For example, the X-Atmosphere-Tracking-uuid will be handshaked before the first application request. A close message will also be sent when the browser tabs/windows are getting close to the server.

readResponseHeaders [default = 'false']

When enableXDR is used or when a request is made via CORS, the browser may refuse to read custom headers like the one Atmosphere is using. Set that value to false to stop reading that value. If enableProtocol is set to true, always set that value to false.

maxReconnectOnClose [default = '5']

The maximum reconnect after a connection is marked as 'dead'. The onError will get called after the maximum is reached.

Functions

callback(AtmosphereResponse) [default = null]

A function that will be invoked during the life cycle of a request. The response's function callback is defined as:

 function(AtmosphereResponse) {
 }

The callback will be invoked every time the request's life cycle events. See AtmosphereResponse.state for a list of life cycle events. It is recommended to use the specific function's callback instead of this request's options: see request.onOpen, request.onClose, request.onMessage etc. for more details.

onOpen(AtmosphereResponse)

Invoked when the connection gets opened.

onClose(AtmosphereResponse)

Invoked when the connection gets closed

onMessage(AtmosphereResponse)

Invoked when a message gets delivered

onError(AtmosphereResponse)

Invoked when an unexpected error occurs

onReconnect(AtmosphereRequest, AtmosphereResponse)

Invoked when the client reconnect to the server

onMessagePublished(AtmosphereRequest, AtmosphereResponse)

Invoked when the request.transport value is polling and a response was sent back by the server.

onTransportFailure(errorMsg, AtmosphereRequest)

Invoked when the request.transport fail because it is not supported by the client or the server. You can reconfigure a new transport (request.transport) from that function.

push(AtmosphereRequest)

Publish or push data to the remote server. Depending on the transport used, a new connection will be used or the same connection re-used. A new connection will be used when selected transport is polling, long-polling, streaming, jsonp or sse. The same connection will be reused if transport is websocket.

push(data)

Same as push(AtmosphereRequest), but by only passing data using {}

AtmosphereResponse

The AtmosphereResponse which gets passed to AtmosphereRequest's function is defined as

status [default = '200']

The HTTP response's status code

reason [default = '']

The HTTP status reason phrase

responseBody [default = '']

The response's body

headers [default = []]

An array of response's headers.

state [default = 'messageReceived']

Indicate the response state. Value can be messageReceived, messagePublished, opening, re-opening, closed, error

transport [default = 'polling']

The transport used between the client and the server. Value are polling, long-polling, streaming, websocket, jsonp, sse.

error [default = null]

The error's message when an unexpected error occurs.

request [default = null]

The AtmosphereRequest that initiated the response.

Example

Creating an AtmosphereRequest

Configuring attributes.

    var request = new $.atmosphere.AtmosphereRequest();
    request.url = document.location.toString() + 'chat';
    request.contentType = "application/json";
    request.transport = 'websocket';
    request.fallbackTransport = 'long-polling';

or

    var request = { url: document.location.host + 'chat',
                    contentType : "application/json",
                    logLevel : 'debug',
                    transport : 'websocket' ,
                    fallbackTransport: 'long-polling'};

Configuring function.

    request.onOpen = function(response) {
        content.html($('<p>',
           { text: 'Atmosphere connected using ' + response.transport }));
        input.removeAttr('disabled').focus();
        status.text('Choose name:');
    };

    request.onReconnect = function (request, response) {
        socket.info("Reconnecting")
    };

    request.onMessage = function (response) {
        var message = response.responseBody;
        try {
            var json = JSON.parse(message);
        } catch (e) {
            console.log('Error: ', message.data);
            return;
        }

        if (!logged) {
            logged = true;
            status.text(myName + ': ').css('color', 'blue');
            input.removeAttr('disabled').focus();
        } else {
            input.removeAttr('disabled');

            var me = json.author == author;
            var date =  typeof(json.time) == 'string' ? 
                 parseInt(json.time) : json.time;
            addMessage(json.author, json.text, me ? 
                  'blue' : 'black', new Date());
        }
    };

    request.onError = function(response) {
        content.html($('<p>', { text: 'Sorry, but '
            + 'there some problem with your '
            + 'socket or the server is down' }));
    };

Subscribing

    var subSocket = socket.subscribe(request);

Publishing

    subSocket.push(JSON.stringify({ author: author, message: msg }));
Clone this wiki locally