I have an application that allows two users to connect to a websocket (which is written in node.js using socket.io). Imagine that the users can deduct a number from 20 (which is defined by the server), each of the two users can do the deduction in a turn-by-turn basis.
My question is, how/where should I setup the 'global' variable of 20? At the moment I set it up when a client connects to the socket but that's incorrect because if we have user 1 connected and he has removed '5' then user 2 (connecting later) should only see that the max number is 15 instead of 20, with my current method user 2 will also see 20. Should I create my varialbe and assign the value '20' to it when I create the http server?
Nothing special is needed for this. It doesn't even have to be global. Just keep it outside of the functions handling the clients' requests.
var sharedNumber = 20;
socket.on('subtractNumber', function (number) {
sharedNumber -= number;
return sharedNumber;
});
socket.on('getNumber', function () {
return sharedNumber;
});