How to get user id using username in io socket

I am using socket io for a chat application. My side is using android. I want to get a specific id. When I submit the username. I want to show user id. I am using the below.

 const userId = user.userId;
 const user1 = usernames[userId];
 console.log("user1 :"+user1);

But this only shows the username, how to show the user ID or how to get the user ID. Please help me?

+4
source share
2 answers

console.log ("user1:" + user1 + "id:" + userId);

0
source

socket.id (), .

  • socket.id

:

var socket = io.connect();
data = {name: userName, userId: socket.id};
socket.emit('setSocketId', data);

:

var userNames = {};
socket.on('setSocketId' function(data) {
    var userName = data.name;
    var userId = data.userId;
    userNames[userName] = userId;
});
  • , , ,

:

var userNames = {};
var getDefaultName = function(){
    var cnt = 0;
    for (user in names) {
        cnt+=1;
    }
    return 'User' + String(cnt);
};
io.sockets.on('connection', function(socket) {
    name = getDefaultName();
    userNames[name] = socket.id;
    data = {name: name};
    socket.emit('initName', data);
});
0

Source: https://habr.com/ru/post/1675016/


All Articles