我正在尝试将所有连接的客户端保存在一个对象中。但正如我所想,连接的客户端都有相同的 id。因此,如果对象connections
具有所有连接的套接字,当我尝试向它发送消息时,connections['mac']
它只会出现在我的屏幕上,就像我发送给我的一样。这是授权代码:
app.post('/auth', function(req, res){ // routes.auth(hash, db, io, pseudoArray, connections)
var username = req.body.username,
password = req.body.password;
if (username != "" && password != ""){
authenticate(username, password, db, hash, function(err, user){
if (user) {
// Regenerate session when signing in
// to prevent fixation
console.log('user authenticated');
req.session.regenerate(function(){
req.session.user = user.name;
req.session.success = 'Authenticated as ' + user.name
+ ' click to <a href="/logout">logout</a>. '
+ ' You may now access <a href="/restricted">/restricted</a>.';
io.sockets.on('connection', function (socket) {
socket.set('pseudo', req.session.user, function(){
pseudoArray.push(req.session.user);
var sessionuser = req.session.user;
socket.emit('pseudoStatus', 'ok');
connections[req.session.user] = socket;
console.log("user " + req.session.user + " connected");
});
});
res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true });
res.redirect('home');
});
} else {
console.log('auth failed');
req.session.error = 'Authentication failed, please check your '
+ ' username and password.'
+ ' (use "tj" and "foobar")';
res.redirect('login');
}
});
} else {
res.redirect('connect');
}
});
我将消息发送给其他客户端的代码:
exports.addfriend = function(connections, io){
return function(req, res){
// var collection = db.get('go1');
var username = req.session.user;
var friend = req.body.name;
console.log(connections[''+friend+'']);
connections[''+friend+''].emit('addRequest', username);
return;
}
}
我之前在路由文件中有这个身份验证代码,我想我应该在 app.js 上运行它。我这样做了,但它仍然无法按我的意愿工作。有人能告诉我我错过了什么吗?