Node.js Frameworks for a Socket.io Server

In several projects, we constructed a Socket.io server using plain Node.js with:

socket.on('eventName', function(data) {})

With everything nested under:

on('connection', function(socket){})

The following example attaches socket.io to a plain Node.JS http server listening on port 3000.

var server = require('http').createServer();

var io = require('socket.io')(server);

io.on('connection', function(client){

  client.on('event', function(data){});

  client.on('disconnect', function(){});

});

server.listen(3000);

This is not an experience I would recommend repeating. You end up with a large list of on blocks, with no structure.

HTTP and Socket.io

The problem is exacerbated when the server also support calls over http. The code has two separate lists, one for http calls and one for socket.io calls. Even if the http calls are structured using a package like journey.

Express

Express separates the socket.io calls from the standard route structure, so again it yields this split brain structure:

var app = require('express')();

var server = require('http').createServer(app);

var express = require('express')

app.get('/', function (req, res) {

  res.send('Hello World!')

})

var io = require('socket.io')(server);

io.on('connection', function(){ /* … */ });

server.listen(3000);

However, later frameworks do better yielding a unified structure, and I would recommend using these.

Sails.js

Sails.js uses a uniform route structure for http and socket calls:

action: function(req, res) {

}

Testing whether the call is via a socket is done with:

req.isSocket

Hapi

Hapi in its plain form is like Express separating http from socket.io calls.

However, a socket.io plugin for hapi lets unify the route structure.

Conclusions

Choose the framework that yields a uniform route structure.