0

我在使用 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 中使用私人消息传递的正确方法吗?

4

0 回答 0