Search icon CANCEL
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Socket.IO Cookbook

You're reading from  Socket.IO Cookbook

Product type Book
Published in Oct 2015
Publisher Packt
ISBN-13 9781785880865
Pages 184 pages
Edition 1st Edition
Languages
Author (1):
Tyson Cadenhead Tyson Cadenhead
Profile icon Tyson Cadenhead

Table of Contents (15) Chapters

Socket.IO Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Wiring It Up 2. Creating Real-Time Dashboards 3. Having Two-Way Conversations 4. Building a Room with a View 5. Securing Your Data 6. Performing a Load Balancing Act 7. Streaming Binary Data 8. Integrating with Mobile Applications 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.

You have been reading a chapter from
Socket.IO Cookbook
Published in: Oct 2015 Publisher: Packt ISBN-13: 9781785880865
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}