我在NodeJS上使用SocketIO作为服务器和Android在客户端发送私人消息时遇到问题。消息没有到达我指定的特定端点,我不明白为什么会这样。 我知道每次用户连接到SocketIO时,都会将他分配给一个特定的套接字ID,我使用客户端名称作为标识符将其保存在与套接字对象一起的对象中。像这样:
// Register your client with the server, providing your username
socket.on('init', function(data) {
console.log("UserID to be assigned to socket: " + data.userID); // Store a reference to your socket ID
// data.userID is identifier with which I find back the respective client I want to send the message to.
connectedSockets[data.userID] = { ID: socket.id, usersocket : socket }; // Store a reference to your socket
console.log("New connected socketID: " + connectedSockets[data.userID].ID + " with socket object: " + connectedSockets[data.userID].usersocket);
});
发送私信时,我想检索此对象,将其发送给相应的人,如下所示:
// Send a message to another user
socket.on('privateMessage', function(data){
// Send message to another user
console.log("ReceivingID : " + data.recipientID);
console.log("SocketID used: " + connectedSockets[data.recipientID].ID);
var userSocket = connectedSockets[data.recipientID].usersocket;
var socketID = connectedSockets[data.recipientID].ID
var recipient = data.recipientID;
io.sockets.userSocket[socketID].emit(recipient, {Message: data.Message});
});
但是,出于某种原因,我的套接字和ID出现了未定义的错误:
var userSocket = connectedSockets[data.recipientID].usersocket;
TypeError: Cannot read property 'usersocket' of undefined
我正在连接两个客户端,两个ID都保存在connectedSockets中,但我仍然收到未定义的错误。
知道为什么会这样吗?
另外,我想知道我是否理解这一点。当想要向特定客户端发送消息时,我正在使用客户端连接时收到的套接字对象和分配给客户端的socketID以使用此命令发出消息:
io.sockets.userSocket[socketID].emit(recipient, {Message: data.Message});
这是在socketIO中使用私人消息的正确方法吗?