更新时间:2023-12-02 13:29:22
我为此所做的是维护一个数据库模型(我使用的是Mongoose),其中包含已连接用户的userId和socketId.您甚至可以使用全局数组来执行此操作.从客户端通过套接字连接,与userId一起发出事件
What i did for this was to maintain a database model(i was using mongoose) containing userId and socketId of connected users. You could even do this with a global array. From client side on socket connect, emit an event along with userId
socket.on('connect', function() {
socket.emit('connected', userName); //userName is unique
})
在服务器端,
var Connect = require('mongoose').model('connect');; /* connect is mongoose model i used to store currently connected users info*/
socket.on('connected', function(user) { // add user data on connection
var c=new Connect({
socketId : socket.id,
client : user
})
c.save(function (err, data) {
if (err) console.log(err);
});
})
socket.on('disconnect', function() { //remove user data from model when a socket disconnects
Connect.findOne({socketId : socket.id}).remove().exec();
})
通过这种方式始终存储已连接的用户信息(当前使用的socketId).每当您需要获取用户当前的socketId时,都将其提取为
This way always have connected user info(currently used socketId) stored. Whenever you need to get a users current socketId fetch it as
Connect.findOne({client : userNameOfUserToFind}).exec(function(err,res) {
if(res!=null)
io.to(res.socketId).emit('my message', msg);
})
我在这里使用了猫鼬,但您甚至可以在此处使用一个数组,并使用过滤器从该数组中获取用户的socketId.
I used mongoose here but you could instead even use an array here and use filters to fetch socketId of a user from the array.