Chapter 9
Going Real-Time with WebSockets
The main reason for using Node is real-time web apps, primarily because Node handles large amounts of I/O gracefully. But it doesn't matter how well your server handles I/O if messages can't be relayed to and from the client in real-time. That's where WebSockets come in—to create an open connection between the server and client, where messages can be streamed in both directions.
In this chapter, you learn why the WebSockets protocol was created and about the traditional approaches it replaces. You then dive right in and create a simple WebSockets app. You use Socket.IO both to create the socket server on Node and to connect to this server from the browser Next, you use Socket.IO to create a real-time chat room app. You find out how to relay messages to and from the server and how to communicate this information to the user. Then you add structure to this app with Backbone.js, adding in support for multiple usernames and timestamps in the chat room. Finally, you persist the data in the app with MongoDB.
This chapter ties together all of the concepts in Part III of this book: Node.js, the Express framework and MongoDB. By the end of the chapter, you'll be comfortable creating your own real-time apps in Node.
How WebSockets Work
To understand how WebSockets work, you first need to understand the conventional approach they were designed to replace. WebSockets are a solution to a long history of polling approaches with inadequate responses ...