Pattle
Pattle

Reputation: 6016

Node.js + Socket.io Storing data in sockets

I am currently building an application using node.js and using the socket.io module. When a user connects I am storing data specific to the user against their socket. For example

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';
    });
});

While this works my question is, is this a good way to do it. I am effectively storing session data but is there a better way to do it?

Upvotes: 11

Views: 7877

Answers (2)

Paulo Coghi
Paulo Coghi

Reputation: 14949

Update: io.set() and io.get() methods are deprecated

A reasonable way is to choose a data store and associate each data with a unique socket identifier (id, for example).


A recommended way is to use the native socket.set and socket.get to set and get data asynchronously specifically to the current socket.

Following your example:

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');
    });
});

Also, you can call a function asynchronously after you set a value:

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

Finally, you can retrieve a variable doing:

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

Or use it directly when needed:

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

Upvotes: 1

Krasimir
Krasimir

Reputation: 13529

I think that you should store those variables in another type of object. Keep the socket object only for the communication. You may generate an unique id for every user and create a map. Something like this:

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';
    });
});

Upvotes: 4

Related Questions