Created
November 28, 2013 19:06
-
-
Save m4tm4t/7696811 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Server Side | |
*/ | |
var players = []; | |
var count = 0; | |
sails.io.on('connection', function (socket) { | |
var player = {}; | |
socket.on('register', function (uuid) { | |
if (!(player = players[uuid])) { // New player | |
count++; | |
console.log('> New player - Total: '+count); | |
player = players[uuid] = {uuid: uuid, tabs: 0}; | |
// Send new counter to all connected players | |
sails.io.sockets.emit('stats', count); | |
} | |
else { | |
// Check for multiple browser tabs opened | |
if (!player.disconnected) { | |
player.tabs++; | |
socket.emit('error', 'too many tabs'); | |
socket.disconnect(); | |
} | |
} | |
// Keep player connected if a refresh occur before timeout | |
if (player.disconnected) { | |
clearTimeout(player.timeout); | |
player.disconnected = false; | |
} | |
socket.emit('stats', count); | |
players[uuid] = player | |
}); | |
socket.on('disconnect', function (type) { | |
// Don't disconnect player in-game | |
if (type == 'booted' && player.tabs > 0) | |
return; | |
player.disconnected = true; | |
player.timeout = setTimeout(function() { | |
if (player.disconnected) { | |
delete players[player.uuid]; | |
count--; | |
console.log('> Player disconnected - Total: '+count); | |
// Send new counter to all connected players | |
sails.io.sockets.emit('stats', count); | |
} | |
}, 2000) | |
}); | |
}); | |
/* | |
* Client side | |
*/ | |
socket.on('connect', function () { | |
if (!(uuid = localStorage.getItem('uuid'))) { | |
var randomlyGeneratedUID = Math.random().toString(36).substring(3,16) + +new Date; | |
localStorage.setItem('uuid', randomlyGeneratedUID); | |
} | |
socket.emit('register', uuid); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment