'How can I get a Socket ID of one user by using username?
I have a problem with my app chat.
For example, if I was admin of a group, I wanted to add one client to my socket room, but I couldn't know his socket ID because it's private. How can I get his socket ID? Can we be able to use his username to find his socket ID?
Solution 1:[1]
When a user makes a socket.io connection to your server, the server will have access to their socket and thus their socket.id at that point. It is up to your application to be able to separately connect that incoming connection with a specific userID in your system. Usually, that is done via a login cookie that will be present when the socket.io connection is first made to your server.
So, at that point of the inbound connection, you should be able to know the socket, the socket.id and the userID in your system. It's up to you to then store that info on your server in a way (often using a Map object with userID as a key and socket as the value) such that you can lookup a userID and get the resulting socket.io socket (which also gives you access to the socket.id).
Upon the disconnect event, you would then remove the connection from the Map object. You might also add the userID as a custom property on the socket object as in socket.userID = xxx which allows you to easily lookup the other way around (get the userID when you have the socket).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jfriend00 |
