Function loading problem Node socket.io

1

I have the following code:

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('chat/index');

        var io = app.get('io');

        io.on("connection", function(socket) {
            console.log("Usuario Conectado");
            socket.on('chat message', function(msg) {
                var userdata = socket.handshake.session.userdata;
                msg = userdata.name + ' : ' + msg;
                io.emit('chat message', msg);
            });

            socket.on("setName", function(name) {
                var msg = 'Usuario ' + name + ' Conectado';
                var userOnline = {
                    'id': socket.id,
                    'name': name
                };
                io.emit('chat message', msg);
                io.emit('user online', userOnline);
                socket.handshake.session.userdata = {
                    'id': socket.id,
                    'name': name
                };
                socket.handshake.session.save();
            });

            socket.on("disconnect", function() {
                var userdata = socket.handshake.session.userdata;
                if (userdata) {
                    var msg = 'Usuario ' + userdata.name + ' Desconectado';
                    io.emit('chat message', msg);
                    io.emit('user offline', userdata.id);
                    delete socket.handshake.session.userdata;
                    socket.handshake.session.save();
                }
                console.log("Usuario Desconectado");

            });
        });

    });
};

Whenever the app.get('/' function is executed it creates a new io.on("connection" connection. This is generating multiple connections to each access. Is there any way to open the connection outside the app.get('/' function?

    
asked by anonymous 28.12.2017 / 19:46

1 answer

0

Not tested but you can try to connect outside of get , something like this:

module.exports = function(app) {

    let io = app.get('io');
    io.on("connection", function(ret) {
        let socket = ret;
    });

    app.get('/', function(req, res) {
    // uso do socket aqui        
    
28.12.2017 / 20:28