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?
socket.id gives the unique id for the socket(client), you can store it in many ways
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;
});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With