简体   繁体   English

如何在socket io中使用用户名获取用户ID

[英]How to get user id using username in socket io

I am using socket io for chat application. 我正在使用socket io进行聊天应用。 My side is using android. 我方是使用android。 I want to get the particular id. 我想获得特定的身份证明。 When i have sending the username. 当我发送用户名时。 I want to show the user id. 我想显示用户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. 但它只显示用户名如何显示用户ID或如何获取用户ID。 Please help me? 请帮我?

socket.id gives the unique id for the socket(client), you can store it in many ways socket.id给出套接字(客户端)的唯一ID,您可以通过多种方式存储它

  • from client side emit the name of the user and socket.id to server 从客户端发出用户名和socket.id发送到服务器

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);
});

console.log(“user1:”+ user1 +“id:”+ userId);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM