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

Managing the socket life cycle


If our server maintains a list of our connected sockets, it should always be mindful of when a socket disconnects.

A socket can disconnect for any number of reasons:

  • The user may navigate away from the web page that the WebSocket connection is on

  • The user's Internet may go down

When these things happen, we can tap into the disconnect event to notify the client side that the socket is no longer available.

How to do it…

To remove references from disconnected sockets, follow these steps:

  1. First, listen for the socket disconnect event on the server side. When this occurs, we will emit an event back to the clients with the ID of the socket that was disconnected. Socket.IO associates every socket with a unique ID, which we can use to manage our sockets. Here is the server-side code:

    io.on('connection', function (socket) {
    io.emit('user.add', socket.id);
    
    socket.on('disconnect', function () {
    io.emit('user.remove', socket.id)
        });
    });
  2. Then, add an element to your view that...