socket.io 使用自定义添加字段获取套接字

socket.io get socket by using custom added field

我在 node.js 项目中使用 socket.io。 我正在使用自定义登录事件进行登录。当用户登录时,我将 userID 保存到套接字中。 我想要的是使用此 userID 字段访问此套接字。我可以使用套接字 ID 访问套接字。

//save user id     
socket.on('login',(userID)=>{
     socket.userID = userID 
})

//also I can access socket using socket id like this
var socketOB = io.sockets.connected[socketID]

但我想使用用户登录时存储的用户 ID 获取套接字

您可以像这样管理套接字对象:

var allSockets = {};


socket.on('login',(userID)=>{
    allSockets[userID] = socket; 
})

socket.on('logout', (userID)=>{
  delete allSockets[userID];
});

其中 userID 是键,socket 是值。

{
  "someUserId" : socketObject,
  "anotherUsedId": socketObject
}