Socket.io: Get ClientID ClientID anywhere

I know how to get the client session id when a user connects.

But I would like to receive it at any time, for example, when a client clicks on something, I would like to know who clicked what session identifier they had.

socket.sessionID does not work, but 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 want the user to join the socket room and also get their sessionID. How could I do this? According to the document, this will be socket.join('room') , but I doubt that socket represents only the connection that I have with the client, and not with other clients. Maybe I just have problems understanding sockets!

+7
javascript sockets express
source share
4 answers

Starting with version 1.0, you get a client session this way:

 var socket = io(); socket.on('connect', function(){ var sessionid = socket.io.engine.id; ... }); 
+19
source share

I'm not sure what you mean because “when the client clicks on something” it means that you mean the “client side” (where you can use socket.socket.sessionid ), but “store it in an array clients, "suggests that you mean the" server side "(where you can access it as socket.id ).

on the 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; ... }); 
+3
source share

I store the client id in server side event handlers just using

 // server.js io.sockets.on('connection', function (client) { client.on('event_name', function (_) { var clientId = this.id; } } 
0
source share

I am using socket.io version 2.0.4 and you can access the client id at any given time using this.id in the handler. For example:

 socket.on('myevent',myhandler); function myhandler(){ console.log('current client id: '+this.id); } 

Obviously, the handler function is executed in the Socket context itself, which will also give you access to other properties, such as client (the connected client object), request (the current processed request object), etc. can see the full API here https://socket.io/docs/server-api/#socket

0
source share

All Articles