Reputation: 3684
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 does socket.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 doubt socket
only represents the connection I have with the client, and not with the other clients. Maybe I'm just having trouble understanding sockets !
Upvotes: 7
Views: 16439
Reputation: 79
I'm using socket.io version 2.0.4 and you can access the client id at any point in time by using this.id
in a handler. For example:
socket.on('myevent',myhandler);
function myhandler(){
console.log('current client id: '+this.id);
}
Apparently the handler function is executed in the Socket context itself, which similarly will give you access to other self-properties like client
(connected Client object), request
(current Request object being processed), etc. You can see the full API here https://socket.io/docs/server-api/#socket
Upvotes: 0
Reputation: 2075
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;
...
});
Upvotes: 19
Reputation: 203241
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;
...
});
Upvotes: 3
Reputation: 8924
I store client id's in server side event handlers simply with:
// server.js
io.sockets.on('connection', function (client) {
client.on('event_name', function (_) {
var clientId = this.id;
}
}
Upvotes: 0