Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 711
DigitalEvolution Avatar asked Dec 13 '25 02:12

DigitalEvolution


2 Answers

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);
like image 184
Melkor Avatar answered Dec 15 '25 16:12

Melkor


Well I solved this out by iterating through the clients list and seeing which one had the socket I wanted

like image 23
DigitalEvolution Avatar answered Dec 15 '25 15:12

DigitalEvolution



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!