Socket.io : Get Client sessionID at any point
Solution 1
As of version 1.0, you get the client's sessionid this way:
var socket = io();
socket.on('connect', function(){
var sessionid = socket.io.engine.id;
...
});
Solution 2
I'm not sure exactly what you mean, because "when the client clicks on something" assumes that you mean 'client-side' (where you can use socket.socket.sessionid
) but "store it in an array of clients" assumes you mean 'server-side' (where you can access it as socket.id
).
Client-side:
var socket = io.connect();
socket.on('connect', function() {
var sessionid = socket.socket.sessionid;
...
});
Server-side:
io.sockets.on('connection', function(socket) {
var sessionid = socket.id;
...
});
Romain Braun
Updated on July 08, 2022Comments
-
Romain Braun almost 2 years
I know how to retrieve the client sessionID when the user connects.
But I'd like to retrieve it at any time, for example when the client clicks on something, I would like to be able to know who clicked, what their sessionID was.
socket.sessionID
doesn't work, nor doessocket.handshake.sessionID
For example :
I have this express route :
.get('/result/:survey', function(req, res) { res.redirect('/result/'+req.params.survey+'/1'); })
Just before the redirection, I'd like to make the user join a socket room, and also get their sessionID. How could I possibly do that ? According to the doc, it would be
socket.join('room')
but I doubtsocket
only represents the connection I have with the client, and not with the other clients. Maybe I'm just having trouble understanding sockets !