I have need to know the current socket ID and index of that socket for a given socket.emit() and corresponding socket.on() in given namespace and room, but I could not find a good reference for how to do this in socket.io documentation.
For instance:
Client
socket.emit('myMessage', myVar);
Server
socket.on('myMessage', function(myVar){
//Need the socket id of the client who just emitted
//and whether or not they are the first socket, second socket, third socket, etc.
// e.g. something like:
currentSocketID = io.socket.connected[socketid]; //?? what is the correct syntax?
currentSocketIndex = io.socket.connected[index[i]]; //?? what is correct syntax?
});
This is not a duplicate of How can I get the socket ID from an event in Socket.io? because I specifically need to evaluate who is the first socket, second socket, etc, then perform some actions based on that information. The stack you linked simply explains how to handle a new message, which is not my issue. I need to handle a new message and reveal the actual socket ID and socket index of the emitter.
Within your callback in this code:
socket.on('myMessage', function(myVar){
// can just use socket.id
});
Which I assume is probably inside of something like this:
io.on('connection', function(socket) {
socket.on('myMessage', function(myVar){
// can just use socket.id
});
});
You have the socket object the client that emitted the message (the socket variable is likely still in scope) so you can just directly access socket.id to get the id of that socket.
You also ask for an index, but you don't say an index of what? There are various data structures in socket.io that keep track of list of sockets in rooms and namespaces. Some are arrays (so they would have an order) and some are maps (so they would not really have an order). As far as I know, socket.io does not provide any documentation about keeping track of some order of sockets in rooms or namespaces. If you explain in more detail what you're trying to do with an index, we might be able to tell you more about what existing data structures might work for you or suggest how you might keep track of this order yourself.