Skip to content

Instantly share code, notes, and snippets.

@pepzwee
Created April 11, 2016 14:22
Show Gist options
  • Save pepzwee/02a2704bff5124fb53af53e1155aac52 to your computer and use it in GitHub Desktop.
Save pepzwee/02a2704bff5124fb53af53e1155aac52 to your computer and use it in GitHub Desktop.
var sitedata = {
connectedUsers: 0
}
io.on('connection', function(socket) {
var userdata = {
joined: false
}
// connected users stuff
socket.on('join', function() {
if(userdata.joined) return; // User already joined
// Set joined to true
userdata.joined = true;
// Add a new user
sitedata.connectedUsers++;
// Emit to all clients how many users are connected
io.emit('connectedUsers', {
num: sitedata.connectedUsers
});
});
// disconnected users stuff
socket.on('disconnect', function() {
// so we don't go -1, -2 (just to be sure, should not happen though)
if(sitedata.connectedUsers > 0) {
// remove the user from connected
sitedata.connectedUsers--;
// emit to all clients new connected user count
io.emit('connectedUsers', {
num: sitedata.connectedUsers
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment