2

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?

2
  • Are you really just storing a number? Do you need to have multiple servers reading/writing from this state? Commented Apr 29, 2013 at 4:04
  • at the moment I'd like to keep things simple (still learning nodejs/socket.io) so there is one server with 2 clients. Commented Apr 29, 2013 at 4:04

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.