在关联数组中进行双重索引 [英] Double indexing in associative array

查看:105
本文介绍了在关联数组中进行双重索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Node.js构建服务器。我将代表我的用户的对象存储在关联数组中,现在这些对象的索引是该连接的套接字标识。使用Socket.io库,我只需要通过socket.id来获得它,因此对于每个处理程序来说,我都可以知道哪个用户提出了请求。



客户端每个用户都有连接用户的ID(与套接字标识不同)。
当我有一个用于从用户发送消息到另一个消息的处理程序时,问题出现了,我举了一个例子:



用户A需要发送给用户B的消息,我的协议指定消息是这样的:

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

服务器端我有一个侦听MSG_KEY的处理程序,该消息发送它被执行,并使用socket.id我可以检索谁发出了请求,但问题是,我需要也得到用户B,但这次使用他的USER_ID。我不想使用socket.id来避免会话欺骗。



我首先想到了在我的数组中索引用户的索引,他们都是从socket.id和用户名。



我的问题是:这样做是个好主意吗?请问socket.io提供了一种简化这种方式的方法吗?

解决方案

没有特别的理由不能做到这一点。我会使用两个单独的对象(地图),并且可能让用户由对象而不是字符串表示,因此实际上只有一个用户(从两个地方引用)。



<例如,用户:

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

然后:

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

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

甚至

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

users.byID [user.userid] = user;
users.bySocket [theSocketID] = user;


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?

解决方案

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;

这篇关于在关联数组中进行双重索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆