Skip to content
Denys Khanzhiyev edited this page Nov 23, 2018 · 2 revisions

The 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

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.

atmosphere.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://

webSocketUrl [default = null]

Useful if you want atmosphere to use a particular url for websocket transport. When webSocketUrl is not defined, url is used instead.

connectTimeout [default = -1]

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

reconnectInterval [default = 0]

The interval in milliseconds 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

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.

dropHeaders [default = 'true']

By default Atmosphere does not add any extra headers to the request. The information like X-Atmosphere-Transport, X-Cache-Date etc. used by the server to track the browser state and the custom headers that you have put in the 'headers' parameter of the AtmosphereRequest are passed as a query string by default (attachHeadersAsQueryString). So if you don't really need that information passed as extra headers, let that value to true and instead let the attachHeadersAsQueryString pass the same information. Letting 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.

pollingInterval [default = '0']

The reconnect interval when long-polling transport is used and a response received.

reconnectOnServerError [default ='true']

By default, if the server respond with a status code higher than 300, a reconnect will be executed and the onReconnect invoked. Setting it to false and the onError function will be called instead.

heartbeat.server [default='null']

The specific interval in seconds of heartbeat sent from the server to this client. The value will be accepted by the server if and only if it's greater than the setting configured on server side. Note that the client does not define himself the interval of heartbeat sent from client to the server. This interval is specifies by the server with this setting.

closeAsync [default = 'false']

When the page is about to reload, atmosphere.js will send a 'close' message to the server synschronously. Set that value to true to send the close asynchronously.

ackInterval [default = '0']

Set that value to the time, in millisecond, to wait for the ACK message from the server. This property only works when atmosphere-postman is used.

reconnectOnServerError [default = 'true']

Set it to false if to prevent atmosphere.js to reconnect when the server is going down.

reconnectOnWindowLocationChange [default = 'false']

Firefox will change the window.location value when a file is downloaded from the same page and will close all connection. To prevent the issue with websocket, set that value to true. The drawback is 2 connections will be made when the page is reloading.

handleOnlineOffline [default = 'true']

Whether atmosphere should handle online/offline events.. The default is to close the connection on an offline event and reconnect automatically on the online event, and generate callback events for each as appropriate). If your app is going to be handling the online/offline events itself it may make sense to disable the automatic atmosphere handling. Each connection is individually configured, so some connections may be automatic, while others handled by the application.

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 reconnects to the server

onMessagePublished(AtmosphereRequest)

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

onClientTimeout(AtmosphereRequest)

Invoked when the request.timeout value expire. An application may decide to reconnect in that case.

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 }));

Step by Step Tutorials

Concepts & Architecture

15 Minutes Tutorial

Advanced Topics

API

Known WebServer Issues

References

External Documentations

githalytics.com alpha

Clone this wiki locally