Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 675
Pattle Avatar asked Aug 19 '13 09:08

Pattle


People also ask

How is data stored in Socket programming?

on("connection", function (socket) { socket. on("save-client-data", function (clientData) { var clientId = clientData. clientId; globalVariable[clientId] = JSON. parse(clientHandshakeData); }); socket.

How do you emit data into a Socket?

To emit an event from your client, use the emit function on the socket object. To handle these events, use the on function on the socket object on your server. Sent an event from the client!

How does Socket.IO work internally?

Socket.IO allows bi-directional communication between client and server. Bi-directional communications are enabled when a client has Socket.IO in the browser, and a server has also integrated the Socket.IO package. While data can be sent in a number of forms, JSON is the simplest.

Is Socket.IO better than WebSocket?

Socket.IO is way more than just a layer above WebSockets, it has different semantics (marks messages with name), and does failovers to different protocols, as well has heartbeating mechanism. More to that attaches ID's to clients on server side, and more.


1 Answers

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';
    });
});
like image 108
Krasimir Avatar answered Sep 20 '22 15:09

Krasimir