2

I'm building a server using Node.js. I store the objects representing my users in an associative array and right now the index of those objects are the sockets id of that connection. Using the Socket.io library i obtain it by simply doing socket.id, so for each handler that takes care of my requests I can always know which user made the request.

Client-side every user has the ids of the connected users (that are different from the socket ids). The problem araises when i have an handler that is used to send a message from an user to another, i make an example:

User A needs to send a message to user B, my protocol specifies the message as something like this:

MSG_KEY:{MSG:'hello world',USER_ID:'12345'}

Server-side i have an handler that listens to "MSG_KEY" and when the message is sent it is executed and using the socket.id I can retrieve who made the request, but the problem is that i need to get also the user B but this time using his USER_ID. I don't want to use the socket.id to avoid session spoofing.

I first thought about indexing in my array the users by indexing them both from socket.id and user id.

My question is: is it a good idea to do this? Does socket.io provide a way to simplify this?

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
MastErAldo
  • 634
  • 3
  • 12
  • 29
  • FWIW, in JavaScript, the term "associative array" is not usually used (just to avoid confusion with arrays -- which is fun, because standard JavaScript arrays aren't really arrays, but never mind). "Map" or just "object" is the normal term. – T.J. Crowder May 15 '13 at 18:25
  • Just to clarify: there is an [edit](http://stackoverflow.com/posts/16572324/edit) link below your question, and you can use that to edit your post whenever needed. Other users can do that too, that's why I added the part you said was missing. And I didn't add the "thank you" part because it's considered unnecessary noise here. – bfavaretto May 15 '13 at 18:45
  • I know, but I was on a mobile connection and it was very unstable, I tried different times to edit the question, but the only thing i managed to do was to add a comment – MastErAldo May 15 '13 at 19:19

1 Answers1

1

There's no particular reason you can't do that. I would use two separate objects (maps), and probably have the users be represented by objects rather than strings so that there was really only one user (referenced from two places).

E.g., a user:

var user = {userid: "JohnD", name: "John Doe"};

and then:

var usersByID = {};
usersByName[user.userid];

and

var usersBySocket = {};
usersBySocket[theSocketID] = user;

Or even

var users = {
    byID:     {},
    bySocket: {}
};

users.byID[user.userid] = user;
users.bySocket[theSocketID] = user;
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875