Separating file server and socket.io logic in node.js

In socket.io 0.8, you should attach events using io.sockets.on('...'), unless you’re using namespaces, you seem to be missing the sockets part:

io.listen(fileserver).sockets.on('connection', handler)

It’s probably better to avoid chaining it that way (you might want to use the io object later). The way I’m doing this right now:

// sockets.js
var socketio = require('socket.io')

module.exports.listen = function(app){
    io = socketio.listen(app)

    users = io.of("https://stackoverflow.com/users")
    users.on('connection', function(socket){
        socket.on ...
    })

    return io
}

Then after creating the server app:

// main.js
var io = require('./lib/sockets').listen(app)

Leave a Comment