AJAX polling request

Usually, a web browser sends requests and immediately receives responses. Every new portion of data requested from the server starts to reload a whole web page. Asynchronous JavaScript and XML (AJAX) is a technology that allows the client-side JavaScript code to request data from a server without the need to reload the current page in the web browser. An important advantage of using AJAX compared to traditional flow of web pages is its ability to bring usability and behavior of desktop applications into a web application. HttpRequest is a client-side XHR request to get data from a URL, formally known as XMLHttpRequest, and has an important role in the AJAX web development technique.

Note

All the requests created within HttpRequest must be in the server from the same origin as the requested resource.

The state of many web applications is inherently volatile. Changes can come from numerous sources, such as other users, external news and data, results of complex calculations, and triggers based on the current time and date. The solution is to periodically issue a request to gain new information. For this purpose, we can use the AJAX polling request technique. Let's take a look at the client side of our web application:

import 'dart:html';
import 'dart:async';
import 'urls.dart' as urls;

var url = "http://${urls.serverAddress}:${urls.serverPort}${urls.dataUrl}";

To print the timestamp, use the following code:

timeStamp() {
  DateTime dt = new DateTime.now();
  return " (${dt.minute}:${dt.second})";
}

The response keeps a request number as follows:

responseHandler(DivElement log, responseText) {
  DivElement item = new DivElement()
  ..text = responseText.toString() + timeStamp;
  // We insert a new element at the top of the log:
  log.insertAdjacentElement('beforebegin', item);
}

void main() {
  DivElement log = querySelector("#log");
  int num = 0;
  // A timer in 2 seconds interval calls the callback function:
  new Timer.periodic(new Duration(seconds: 2), (Timer timer) {
    // We generate the query parameter with number:
    String query = "number=${num++}";
    HttpRequest.getString("$url?$query")
      .then((response) => responseHandler(log, response));
  });
}

This is a simple implementation that creates new requests in every 2 seconds. Each request has a unique number; when the server returns it, this helps us check the order of responses. We'll make small changes to the server code to add some random generated data to the response. The readyChecker variable is a random generator whose values determine whether the data is ready to be fetched. The dataGenerator variable is a random generator of integer numbers in a range between 0 and 100, as shown in the following code:

import 'dart:math';
Random readyChecker = new Random(
  new DateTime.now().millisecondsSinceEpoch);
Random dataGenerator = new Random(
  new DateTime.now().millisecondsSinceEpoch);
//…
In the fetchData function, we check whether the data is ready to be fetched or returns an empty string:
String fetchData() {
  if (ready.nextBool()) {
    return data.nextInt(100).toString();
  } else {
    return "";
  }
}

In the following code, we add the fetched data to the response:

processQueryParams(HttpRequest request) {
  setHeaders(request);
  request.response.write(
      "${request.method}: ${request.uri.path}");
  request.response.write(", Data:" + fetchData());
  if (request.uri.queryParameters.length > 0) {
    request.response.write(", Params:" + 
        request.uri.queryParameters.toString());
  }
  request.response.close();
}

Create a Dartium launch configuration and open the index.html file in the web browser. Run the server and launch a new configuration to see the following result:

GET: /data, Data:4, Params:{number: 0} (31:28)
GET: /data, Data:26, Params:{number: 1} (31:30)
GET: /data, Data: , Params:{number: 2} (31:32)
GET: /data, Data: , Params:{number: 3} (31:34)
GET: /data, Data:47, Params:{number: 4} (31:36)
GET: /data, Data:69, Params:{number: 5} (31:38)
GET: /data, Data: , Params:{number: 6} (31:40)
GET: /data, Data: , Params:{number: 7} (31:42)
GET: /data, Data:98, Params:{number: 8} (31:44)

The polling requests have the following disadvantages:

  • Periodical requests consume bandwidth and server resources
  • The server must always respond with or without data; as a result, the client receives a lot empty strings

Let's try to use the AJAX long polling request to fix them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.137