Question

I'm trying to seperate my socket.io code in my app to it's own file like the answer in this thread: Separating file server and socket.io logic in node.js

However, the socket.io code never runs and will not start to listen and I don't really understand why:

//index.js
kraken.create(app).listen(function (err, server) {
        if (err) {
            console.error(err);
        }
        var io = require('./lib/socket').listen(server);
    });

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

module.exports.listen = function(app) {
    return function (req, res) {
        io = socketio.listen(app);

        io.sockets.on('connection', function (socket) {

            socket.on('disconnect', function () {
                if (socket.uid !== undefined) {
                    // do some stuff
                }
            });
        });

        return io;
    }
};

My best guess is that the req and res objects doesn't exist since it's not a request? The problem is that I really need to use the req object since I need to access the session during connect. If this is the issue, how can achieve that?

Thanks in advance for your sage advice and better wisdom.

EDIT: I have looked at https://github.com/jfromaniello/passport.socketio which is kinda exactly what I need, however I don't know what my session key or secret is. How can I know that with passport?

Était-ce utile?

La solution

Your listen function is just returning another function and not actually triggering the code to setup socketio to listen.

Try:

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

    io.sockets.on('connection', function (socket) {

        socket.on('disconnect', function () {
            if (socket.uid !== undefined) {
                // do some stuff
            }
        });
    });

    return io;
};

Here's another example: https://github.com/paypal/kraken-js/issues/39

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top