Last Updated: February 25, 2016
·
768
· bajalovic

Websocket with Ajax Polling support

I had a task to display some data updates in real time, and I decided to use websockets. Once I implemented websockets, I decided to go a little further and to add an Ajax Polling support for browsers that do not have support for websockets.

var ajaxPolling = false;
var ajaxPollingTimeout = null;
var ajaxPollingTimer = 5; // seconds
var websocketPolling = true;
var websocketReconnectTimer = 2; // seconds
var timerIncrease = 2;
var conn = null;

startWebsocketConnection();

function startWebsocketConnection() {
    conn = new ab.Session(
            'ws://localhost:8080'
            , function() {            // Once the connection has been established
                console.log("Opened connection");
                // set websocketPolling to true and reset reconnect timer
                websocketPolling = true;
                websocketReconnectTimer = 2; // seconds 
                stopAjaxPolling(); // stop ajax polling if any

                conn.subscribe('some-topic', function(topic, data) {
                    // handle data
                });
            }
            , function() {            // When the connection is closed or do not exist
                console.warn('WebSocket connection closed');
                startAjaxPolling();

                startReconnectingWebsocketConnection();
            }
            , { 
                'skipSubprotocolCheck': true
            }
    );
}

function AjaxPolling() {
    if(!ajaxPolling) { // if ajaxPolling is false, go out ;)
        stopAjaxPolling();
        return;
    }

    $.ajax({
        url: '/get-data',
        type: 'GET',
        dataType: 'JSON',
        success: function(data) {
            // handle data

            // set timeout to make another ajax request
            ajaxPollingTimeout = setTimeout(function() {
                AjaxPolling();
            }, ajaxPollingTimer * 1000);
        }
    });
}

function startReconnectingWebsocketConnection() {
    websocketPolling = false;
    // set timer, it will call startWebsocketConnection() method for 4s, 8s, 16s, 32s, ...
    websocketReconnectTimer = websocketReconnectTimer * timerIncrease;
    setTimeout(function() {
        startWebsocketConnection();
    }, websocketReconnectTimer * 1000);
}

function startAjaxPolling() {
    if(!ajaxPolling) {
        ajaxPolling = true;
        AjaxPolling();
    }
}

function stopAjaxPolling() {
    ajaxPolling = false;
    if(ajaxPollingTimeout)
        clearTimeout(ajaxPollingTimeout);
}