November 14, 2009

Server push demo

In this demo, I use two XMLHttpRequests ? one is a regular request to submit messages to the server, while the second one is the push channel to get messages from the server. The first XMLHttpRequest is easy. When you press enter, the browser initiates this request, and sends the message entered to the server. It then waits for the server to acknowledge the message. The server processes this message and acknowledges by either asking the browser to initiate the push channel, and a simple OK. The push channel is based on a technique described in Server Push and Server Sockets. In this technique, the push channel returns a multipart response with content type multipart/x-mixed-replace. Whenever a new chat message arrives, the server writes a MIME part containing the message. Here is an example message:





You said: Knock knock



--goofup101
Content-type: text/xml


You said: Who's there?



--goofup101--
On the browser side, we need to be able to process each part without waiting for the complete multipart message to arrive. This can be done via the onload handler of XMLHttpRequest. Here is an example. The onload handler in this example gets called whenever a new chat message arrives.


var channel = ...; // Create XMLHttpRequest
channel.multipart = true;
channel.onload = function(e)
{
var message;
if(this.responseXML) {
message = this.responseXML;
}
else {
message = this.event.target.responseXML;
}

// Process the message
};
...
channel.open('GET', url, true);
channel.send(null);
...


These are the easier problems to solve. For the server push to work effeciently and effectively, managing connections is critical for both the browser and the server