Tojó Tojó - 1 month ago 14
Javascript Question

Express - socket.io - session. Refer to user id as socket id

I am using express-socket.io-session. I think I was able to setup the basic config by seeing the tutorials:

//BASIC CONFIG?

var clients = [];

var session = require("express-session")({
secret: 'some key',
resave: true,
saveUninitialized: true
});
var sharedsession = require("express-socket.io-session");
app.use(session);

io.use(function(socket, next){
next();
});

io.use(sharedsession(session, {
autoSave:true
}));

io.on('connection', function(socket) {

console.log("CLIENT CONNECTED");
var session = socket.handshake.session;
clients.push(socket);

socket.on('disconnect', function() {
console.log("CLIENT DISCONNECTED");
});

});


What I want to be able to do now is to refer to a specific client socket not by the socket but by the session id that should be assigned to that socket. When a user logins this happens:

req.session.user_id = user_id;
//(user_id is equal to DB {0,1,2,3...} ids


I was able to send sockets to specific clients when I did this:

clients[0].emit("to_do",info); // I don't know who is client index 0 compared to the login reference...


I would like to be able to do this or similar:

user_id = 3; // which would have a socket assigned

clients(user_id).emit("to_do",info);


That would mean each client would have a socket assigned to its previously assigned id. How could I do this so I could specify the socket by that id? I am not experienced at all with all of this so sorry for any big mistakes. Thanks

Answer

Your problem can be solved by each socket joining a group named after it's id:

socket.join(socket.id);

io.sockets.in(socket.id).emit('to_do', info);

//or

io.sockets.in(clients[0].id).emit('to_do', info);