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

Creating an Express server with Socket.IO


Express is probably the most widely used Node application framework available. Numerous MVC frameworks are written based on Express, but it can also be used on its own. Express is simple, flexible, and unopinionated, which makes it a pleasure to work with.

Socket.IO can be used based on the Express server just as easily as it can run on a standard Node HTTP server. In this section, we will fire the Express server and ensure that it can talk to the client side via Socket.IO.

Getting ready

The Express framework runs on Node, so you will need to have Node installed on your machine. Refer to the previous recipe for instructions on how to install Node and Socket.IO.

In addition to Node and Socket.IO, you will also need to install the Express npm package. Express can be installed by entering npm install express --save on your terminal.

How to do it…

Follow these steps to create an Express server using Socket.IO:

  1. You will need to create a new server-side JavaScript file called server.js. It will contain all of your server instantiation and handle your Socket.IO messaging. The server.js file will look similar to the following code:

    var express = require('express'),
        app = express(),
        http = require('http'),
        socketIO = require('socket.io'),
        server, io;
    
    app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
    });
    
    server = http.Server(app);
    server.listen(5000);
    
    io = socketIO(server);
    
    io.on('connection', function (socket) {
      socket.emit('greeting-from-server', {
          greeting: 'Hello Client'
      });
      socket.on('greeting-from-client', function (message) {
        console.log(message);
      });
    });
  2. The server.js file will serve a static HTML file called index when the user navigates to the root directory of the server. The HTML file will handle the client-side Socket.IO messaging. It will look similar to the following code:

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <script src="/socket.io/socket.io.js"></script>
    <script>
                var socket = io('http://localhost:5000');
                socket.on('greeting-from-server', function (message) {
                    document.body.appendChild(
                        document.createTextNode(message.greeting)
                    );
                    socket.emit('greeting-from-client', {
                        greeting: 'Hello Server'
                    });
                });
    </script>
    </body>
    </html>
  3. Once both of your files are created, you can start your server by entering node server on your terminal.

  4. After the server starts, you should be able to navigate to http://localhost:5000 and see a message that says Hello Client:

  5. There should be a message that says 'Hello Server' on your terminal:

Awesome! Now you've got Socket.IO running on Express.

How it works…

Express is a collection of HTTP utilities and middleware that make it easier to use Node as a web server. Although Express provides a robust API that isn't available out of the box from the built-in Node HTTP module, using Express with Socket.IO is still very similar.

We created a new Express server with var app = express(). We passed this to the http.Server() method. By passing our Express app as the first argument to the HTTP server, we told Node that we wanted to use Express as our handler for HTTP requests.

Next, we passed the HTTP server directly to the SocketIO method exactly as we would have if we were using a nonExpress HTTP server. Socket.IO took the server instance to listen for new socket connections on it. The new connections came from the client side when we navigated to the page in our browser.

See also

Creating a Node HTTP server with Socket.IO.