当他们的socket id直接存储在io.sockets.on('connect')函数中时,我似乎只能向用户发出消息。 我不知道为什么在他们登录后尝试存储他们的套接字ID时它不起作用。
工作:
var clients = {};
/** A new socket connection has been accepted */
io.sockets.on('connection', function (socket)
{
//Used to access session id
var hs = socket.handshake;
clients[socket.id] = socket; // add the client data to the hash
users['brownj2'] = socket.id; // connected user with its socket.id
socket.on('user-login', function(user){
if(!users[username]){
//users[username] = socket.id; // connected user with its socket.id
}
})
socket.on('page-load', function(pid)
{
if(users['brownj2'])
{
clients[users['brownj2']].emit('hello');
}
else
{
console.log("NOT FOUND BROWNJ2");
}
}
}
不工作:
var clients = {};
/** A new socket connection has been accepted */
io.sockets.on('connection', function (socket)
{
//Used to access session id
var hs = socket.handshake;
clients[socket.id] = socket; // add the client data to the hash
socket.on('user-login', function(user){
if(!users['brownj2']){
users['brownj2'] = socket.id; // connected user with its socket.id
}
})
socket.on('page-load', function(pid)
{
if(users['brownj2'])
{
clients[users['brownj2']].emit('hello');
}
else
{
console.log("NOT FOUND BROWNJ2");
}
}
}
JavaScript客户端代码段
var socket = io.connect('');
socket.on("hello", function(){
alert("Hi Jack");
console.log("WEBSOCKET RECIEVED");
})
解决方案:感谢@alessioalex我必须从登录页面删除对socket.io的引用,并将以下内容添加到io.sockets.on('connection')中
var hs = socket.handshake;
sessionStore.get(hs.sessionID, function(err, session){
console.log("SESSION: " + util.inspect(session));
clients[socket.id] = socket; // add the client data to the hash
validUsers[session.username] = socket.id; // connected user with its socket.id
})