Node.js + Socket.io将数据存储在套接字中

我目前正在使用node.js和使用socket.io模块构build一个应用程序。 当用户连接时,我将特定于用户的数据存储在其套接字中。 例如

io.sockets.on('connection', function (socket) { socket.on('sendmessage', function (data, type) { socket.variable1 = 'some value'; socket.variable2 = 'Another value'; socket.variable3 = 'Yet another value'; }); }); 

虽然这工作,我的问题是,这是一个很好的方法来做到这一点。 我正在有效地存储会话数据,但有没有更好的方法来做到这一点?

我认为你应该将这些variables存储在另一种types的对象中。 保持套接字对象仅用于通信。 您可以为每个用户生成一个唯一的ID并创build一个地图。 像这样的东西:

 var map = {}, numOfUsers = 0; io.sockets.on('connection', function (socket) { numOfUsers += 1; var user = map["user" + numOfUsers] = {}; socket.on('sendmessage', function (data, type) { user.variable1 = 'some value'; user.variable2 = 'Another value'; user.variable3 = 'Yet another value'; }); }); 

更新:不推荐使用io.set()io.get()方法

一个合理的方法是select一个数据存储并将每个数据与一个唯一的套接字标识符(例如id)相关联。


推荐的方法是使用本地socket.setsocket.get来asynchronous设置和获取当前套接字的数据。

遵循你的例子:

 io.sockets.on('connection', function (socket) { socket.on('sendmessage', function (data, type) { socket.set('variable1', 'some value'); socket.set('variable2', 'Another value'); socket.set('variable3', 'Yet another value'); }); }); 

另外,您可以在设置一个值之后asynchronous调用一个函数:

 ... socket.set('variable1', 'some value', function () { /* something to be done after "variable1" is set */ }); ... 

最后,你可以检索一个variables:

 ... var variable1 = socket.get('variable1') ... 

或者在需要时直接使用它:

 if ( socket.get('age') > 30 ) { // Vida longa às eleições presidenciais diretas no Brasil }