我正在尝试将所有连接的套接字存储在像
这样的数组中var basket = {};
io.sockets.on('connection', function (socket) {
socket.on("register", function(user_profile) {
basket[user_profile.id] = socket.id;
});
socket.on(SEND_INVITE,function(invitation_details){
var to = basket[invitation_details.invitee];
io.sockets.socket(to).emit(RECIEVE_INVITE,invitation_details);
});
});
`
但是我不知道代码中有什么不对,只有最后加入的客户端才会存储在篮子里。请帮帮我
答案 0 :(得分:4)
这就是我在我创建的项目中完成的方式。我使用了用户名作为密钥,而socket.id作为值。然后在客户端哈希中我使用socket.id作为键,并使用套接字作为值。这使我可以根据用户名轻松地向“有效”用户发送消息。
var validUsers = {};
var clients = {};
io.sockets.on('connection', function (socket)
{
var hs = socket.handshake;
if(hs.session)
{
if(hs.session.username)
{
clients[socket.id] = socket; // add the client data to the hash
validUsers[hs.session.username] = socket.id; // connected user with its socket.id
}
}
...
clients[validUsers[username]].emit('move-story', data);
}
//Auth the user
io.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
data.cookie = parseCookie(data.headers.cookie);
data.sessionID = data.cookie['express.sid'];
//Save the session store to the data object
data.sessionStore = sessionStore;
sessionStore.get(data.sessionID, function(err, session){
if(err) throw err;
if(!session)
{
console.error("Error whilst authorizing websocket handshake");
accept('Error', false);
}
else
{
console.log("AUTH USERNAME: " + session.username);
if(session.username){
data.session = new Session(data, session);
accept(null, true);
}else {
accept('Invalid User', false);
}
}
})
} else {
console.error("No cookie was found whilst authorizing websocket handshake");
return accept('No cookie transmitted.', false);
}
});