Double indexing in associative array

我们两清 提交于 2019-12-12 18:07:19

问题


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?


回答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;


来源:https://stackoverflow.com/questions/16572324/double-indexing-in-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!