HTML and CSS Reference
In-Depth Information
13.4.6 Tracking Requests and Received Data
When polling, we need to know what data to retrieve on each request. With long
polling, the client polls the server; the server keeps the connection until new data is
available, passes it, and closes. Even if the client immediately makes another request,
there is a risk of loosing data between requests. This situation gets even worse
with normal polling. How will the server know what data to send back on a given
request?
To be sure all the data makes it to the client, we need a token to track requests.
Ideally, the server should not need to keep track of its clients. When polling a single
source of data, such as “tweets” on Twitter, a reasonable token could be the unique
id of the last tweet received by the client. The client sends the id with each request,
instructing the server to respond with any newer tweets.
In the case of the Comet client, we expect it to handle all kinds of data streams,
and unless the server uses some kind of universally unique id, we cannot rely on the
id token. Another possibility is to have the client pass along a timestamp indicating
when the previous request finished. In other words, the client asks the server to
respond with all data that was created since the last request finished. This approach
has a major disadvantage; it assumes that the client and server are in sync, possibly
down to millisecond granularity and beyond. Such an approach is so fragile it cannot
even be expected to work reliably with clients in the same time zone.
An alternative solution is to have the server return a token with each response.
The kind of token can be decided by the server, all the client needs to do is to
include it in the following request. This model works well with both the id and
timestamp approaches as well as others. The client doesn't even know what the
token represents.
To include the token in the request, a custom request header or a URL parameter
are both good choices. We will make the Comet client pass it along as a request
header, called X-Access-Token . The server will respond with data guaranteed
to be newer than data represented by the token.
Listing 13.66 expects the custom header to be provided.
Listing 13.66 Expecting the custom header to be set
"test should provide custom header": function () {
this.client.connect();
assertNotUndefined(this.xhr.headers["X-Access-Token"]);
}
This test fails as expected, and the implementation can be seen in Listing 13.67.
Search WWH ::




Custom Search