Exchanging real-time messages using WebSockets

Before HTML5 Web Sockets, web applications that needed to implement real-time updates, such as chat messages and game moves, had to resort to inefficient methods.

The most popular method was to use long polling, where a connection to the server is kept open until an event arrives. Another popular method was streaming chunked blocks of JavaScript to an iframe element, also known as comet streaming .

HTML5 WebSockets enable the exchange of real-time messages with the web server. The API is much cleaner and easier to use, less error-prone, and provides lower message latency.

In this recipe, we're going to implement a simple chat system based on WebSockets. To make the system easier to extend, we're going ...

Get HTML5 Data and Services Cookbook 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.