Book Image

Socket.IO Cookbook

By : Tyson Cadenhead
Book Image

Socket.IO Cookbook

By: Tyson Cadenhead

Overview of this book

Socket.IO is a JavaScript library that provides you with the ability to implement real-time analytics, binary streaming, instant messaging, and document collaboration. It has two parts: a client-side library that runs in the browser, and a server-side library for node.js. Socket.IO is event-driven and primarily uses the WebSocket protocol that allows us to emit data bi-directionally from the server and the client. Socket.IO This book is a complete resource, covering topics from webSocket security to scaling the server-side of a Socket.IO application and everything in between. This book will provide real-world examples of how secure bi-directional, full-duplex connections that can be created using Socket.IO for different environments. It will also explain how the connection vulnerabilities can be resolved for large numbers of users and huge amounts of data/messages. By the end of the book, you will be a competent Socket.IO developer. With the help of the examples and real-world solutions,you will learn to create fast, scalable, and dynamic real-time apps by creating efficient messaging systems between the server side and the client side using Socket.IO.
Table of Contents (15 chapters)
Socket.IO Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Introduction


Socket.IO is a powerful tool for creating real-time applications with bidirectional communication between the server side and the client side. It leverages the power of WebSockets along with several fallbacks, including JSON long polling and JSONP long polling through a single unified API. It can be used to create bidirectional interactions, such as real-time dashboards, chat applications, and multiplayer games.

In my previous jobs, I created several real-time JavaScript dashboards predating the Socket.IO library. During that time, I felt the pain of not having a good solution for true real-time communication. I found myself using hacks to obtain new data from the user interface. One method was to pound the server with an Ajax call every few seconds. The server had no way of knowing whether anything had updated since the last request, so it would dump all the data into the huge JSON object. It was up to the client-side JavaScript application to search the data and check whether there were any updates. If there were updates, the client side was responsible for updating the display as needed. This turned out to be difficult to maintain and a nightmare to debug. When Socket.IO was released, I was blown away. Now, I could send only the pieces of data that had actually been updated from the server instead of pushing up everything. Instead of setting an interval to make Ajax calls, I could just send data when new data came in. In short, Socket.IO made my life easier.

Socket.IO is an open source library created by Guillermo Rauch. It is built with Engine.IO, which is a lower-level abstraction on top of the WebSocket technology. Socket.IO is used to communicate bidirectionally between the server side and the client side in a syntax that looks as if you are just triggering and listening to events. The WebSocket API protocol was standardized in 2011. It is a Transmission Control Protocol (TCP) that only relies on HTTP for its initial handshake. After the handshake is complete, the connection is left open so that the server and the client can pass messages back and forth as needed.

For reference, a typical WebSocket connection without Socket.IO will look something similar to the following code on the client side:

Note

We are not falling back for browsers that do not support WebSockets.

if ('Websocket' in window) {
    var ws = new WebSocket('ws://localhost:5000/channel');
    
    ws.onopen = function () {
        ws.send('Hello world');
    };
    
    ws.onmessage = function (e) {
        console.log(e.data);
    };
    
    ws.onclose = function () {
        console.warn('WebSocket disconnected');
    }

} else {
    throw new Error('This browser does not support websockets');
}

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Socket.IO goes a step beyond just providing an easy-to-use and more robust API on top of WebSockets. It also provides the ability to seamlessly use other real-time protocols if WebSockets are not available. For example, it will fall back on JSON long polling in the absence of WebSocket support. Long polling is essentially a trick to emulate the WebSocket behavior in browsers that don't support WebSockets. After a long polling request is made, it is held onto by the server instead of immediately responding as a traditional HTTP request would. When data becomes available, the long polling request is resolved, closing the loop of the long request cycle. At this point, a new long polling request will typically be made. This gives the illusion of the continuous connection that WebSockets provides. Although long polling is less than ideal in the landscape of modern technology, it is a perfect fallback when needed. When you send a message with Socket.IO, the API for WebSockets and long polling are identical, so you don't have to deal with the mental overhead of integrating two syntactically different technologies.

Although there are Socket.IO implementations in many server-side languages, we will use Node.js in this book. With Node.js, we can write JavaScript on the server side, which gives us a single syntax on the server and client.

In this chapter, we will create a Node server with Socket.IO and obtain some very basic cross-browser messaging working. We will also look at debugging tools that make working with Socket.IO even easier.