Function loading problem Node socket.io

Asked

Viewed 86 times

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");

            });
        });

    });
};

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

1 answer

0

Untested but you can try to connect outside the get, something like that:

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        
  • already tried this before but it returns the following error: io.on("Connection", Function(Ret) { Typeerror: Cannot read Property 'on' of Undefined

  • It means that the app.get('io'); is not working (or is asynchronous).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.