Search code examples
node.jssocket.ioexpress-4

Adding Socket.io to an Express 4 Server - multiple file setup


I've been bouncing back and forth between socket.io and express.io - but settled for socket.io with Express 4, as I would like to use Namespaces.

I have worked on some examples of having an Express 4 Server using Socket.io - but most examples are based on one file with everything in it. I am trying to separate all my code to make it easier but I am at a loss as to how to add Socket.io (or where).

I have index.js which uses Cluster and basically calls server.js:

var server = require( "./server.js" );
var cluster = require('cluster');

var webApp={
    run: function(){
      console.log('Starting: Server');
      server.listen();
    }
};

if(cluster.isMaster){
    cluster.fork();
    cluster.on('exit',function(worker){
      console.log('Worker ' + worker.id + ' died..');
      setTimeout( function () { cluster.fork(); }, 1000 );
    });
} else{
    try {
        webApp.run();
    }
    catch(e)
    {
        console.log(e);
        process.exit(1);
    }
    process.on('uncaughtException', function(err){
        console.log(err);
        process.exit(1);
    });
    process.on( 'SIGINT', function () {
      console.log( "\n SIGINT (Crtl-C)" );
        //Kill worker
        cluster.disconnect();
        process.exit(1);
    });
}

This then calls the server.js file:

var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var config = require('./config/config.js');
var router = require('./routes');

var Server = Object.subClass({
  /**
     * Constructor
     */
  init:function(){
    this.appServer = express();
    var that = this;
    var appServer = this.appServer;

    appServer.use(express.static(__dirname + '/public'));
    appServer.set('views', path.join(__dirname, 'views'));
    appServer.set('view engine', 'ejs');
    appServer.use(bodyParser.urlencoded({ extended: true }));
    appServer.use(bodyParser.json());
    appServer.get('/',router.root);
  },
  /**
    * Listener HTTP
    */
  listen:function(){
    var port = config.rest.port;
    console.log(':: on port:' + port);
    this.appServer.listen(port);
  }
});

module.exports = new Server();

I am only having one 'route', which is the '/' and is defined in routes.js file. The page loads fine but where do I add the server side socket.io? and do I add any socket.io namespace definitions in the routes.js file or in the javascript of the page being loaded?

There are so many ways of using sockets that I can't seem to work out the best approach for my multi-file approach.

Any help would be brilliant as I seem to be going in circles.

Enjoy our Saturday :)

Thanks again.


Solution

  • I've spent the morning looking at the Cluster/Worker approach and decided to use 'SocketCluster' as it seems to do what I need.

    Enjoy your Sunday