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

后端 未结 4 1249
栀梦
栀梦 2020-12-04 05:58

I\'m fairly new to node.js and I\'ve found its quite complicated separating a project into multiple files as the project grows in size. I had one large file before which ser

4条回答
  •  囚心锁ツ
    2020-12-04 06:45

    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('/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)
    

提交回复
热议问题