I've been working on setting up a chatroom, but I've noticed that each time the page refreshes, more connections are being established. It's interesting because initially only one connection is created when I visit the chat room page. However, after just one refresh, two clients are connected. And with each subsequent refresh, an additional connection is added.
Here is the code for my chat route:
/* GET home page. */
router.get('/', accessControl.ensureAuthenticated, function(req, res, next) {
const io = req.app.io;
console.log('const io created');
io.on('connection', function(socket){
console.log(' %s sockets connected', io.engine.clientsCount);
console.log('[NodeApp] (socket.io) A client has connected');
socket.on('chat message', function(message){
if (message.sessionID == req.session.id) {
io.emit('chat message', message);
console.log('message: ' + message.message);
} else {
console.log('client sessionID ('+message.sessionID+') does not match server sessionID ('+req.session.id+')');
}
});
socket.on('disconnect', function(){
console.log('[NodeApp] (socket.io) A client has disconnected');
socket.disconnect();
});
});
res.render('chat/index', {
title: "Chat",
//send session id for client verification
sessionID: req.session.id,
});
});
When the chat page is refreshed three times, here is the output:
const io created
1 sockets connected
[NodeApp] (socket.io) A client has connected
const io created
[NodeApp] (socket.io) A client has disconnected
1 sockets connected
[NodeApp] (socket.io) A client has connected
1 sockets connected
[NodeApp] (socket.io) A client has connected
const io created
[NodeApp] (socket.io) A client has disconnected
[NodeApp] (socket.io) A client has disconnected
1 sockets connected
[NodeApp] (socket.io) A client has connected
1 sockets connected
[NodeApp] (socket.io) A client has connected
1 sockets connected
[NodeApp] (socket.io) A client has connected
message: test message (should be sent 3 times)
message: test message (should be sent 3 times)
message: test message (should be sent 3 times)