Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user id using username in socket io

I am using socket io for chat application. My side is using android. I want to get the particular id. When i have sending the username. I want to show the user id. I have use the shown below.

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

But it shows only the username how to show the user id or how to get the user id. Please help me?

like image 967
Fazil Avatar asked Apr 18 '17 05:04

Fazil


1 Answers

socket.id gives the unique id for the socket(client), you can store it in many ways

  • from client side emit the name of the user and socket.id to server

Client side:

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

Server side:

var userNames = {};
socket.on('setSocketId' function(data) {
    var userName = data.name;
    var userId = data.userId;
    userNames[userName] = userId;
});
  • you can do it on server side also when socket gets connected but you have to give some default name to user and then emit the client the default name

Server side:

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);
});
like image 60
vsri293 Avatar answered Oct 25 '22 05:10

vsri293