Josh
Josh

Reputation: 13818

Socket.io client specific variable

How do I store session specific info in Socket.io?

var client={}; //is this static across all sockets (or connected clients) that are connected? 
io.on('connection', function(socket){

  client.connectiontime=Date.now();
});


//on another io.on('connection') for the same connected client
io.on('connection', function(socket){
 store(client.connectiontime);
}

How do I use the client variable only for the operations related to the currently connected client if it is considered static?

Upvotes: 1

Views: 1264

Answers (1)

KM529
KM529

Reputation: 402

First, each socket is given a name that can be used to refer to it, but that changes each time the same client connects so this would not be useful if it is supposed to remain after the client leaves. If your goal is to store the connection time somewhere (a database?) then you would have to get a unique identifier from the client that could be used to find them again similar to a login. You would then pass the date object into the function that handles storing that time.

You should note though, that 'connection' is only called the first time the socket connects. A connection is not the event you normally would be using for when a client does something unless they disconnects between each access of the server program.

If you are sure you want to just use the Client object, you would likely have to create a client array and use the socket id as a key to access the object later. You would then have something like

array[socket.id].connectiontime = Date.now()

var client={}; //is this static across all sockets (or connected clients) that are connected? 
var clients = [];
io.on('connection', function(socket){
  clients[] = {
                id : socket.id
                connectiontime : Date.now()
  }
});


//on another io.on('connection') for the same connected client
io.on('connection', function(socket){
// Here you would search for the object by socket.id and then store
 store(client.connectiontime);
}

Upvotes: 2

Related Questions