Chapter 9. Web Sockets

HTTP is a request and response protocol. It was designed to request files and still operates around the idea of file requests. For the type of application that has to load data and then save it later, this works pretty well.

However, for an application that needs real-time data from the server, this works quite poorly. Many classes of applications require real-time or semi-real-time access to the server. Applications such as chat, or those that share data in real time like many of the Google Office applications, really need a way for the server to push data to the browser when things happen on the server. There are a few ways to do this with HTTP, but none of them really work well.

Some applications, such as Gmail, simply make a large sequence of HTTP requests, more than one per second, as shown in Figure 9-1. This has a lot of overhead and is not a particularly efficient way to poll the server. It can also create a huge amount of server load, as each request involves a setup and teardown that may need to happen on the server. Plus, there is the network overhead of HTTP headers, as well as user authentication. The HTTP headers can add a few hundred bytes to each request. In a busy server this can add a significant amount of load to the servers and network.

A second method is to open up an HTTP request to the server and let it hang open. When the server needs to send some data, it sends it to the client and then closes the HTTP request. At this point the browser ...

Get Programming HTML5 Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.