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?