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('/'
?
already tried this before but it returns the following error: io.on("Connection", Function(Ret) { Typeerror: Cannot read Property 'on' of Undefined
– Alexandre Simon
It means that the
app.get('io');
is not working (or is asynchronous).– BrTkCa