Approach of sending private messages to specific clients in SocketIO and Android

364 Views Asked by At

I have a problem with sending private messages using SocketIO on NodeJS as a Server and Android on the client side. The messages do not reach the specific endpoint that I have assigned and I do not understand why that is. I know that each time a user connects to SocketIO, he is assigned to a specific socket ID which I save in an object alongside with the socket object using the client name as an identifier. Like so:

  // 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);
});

When sending a private message, I want to retrieve this object to send it to the respective person like so:

// 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});

});

However, for some reason I get an undefined error for my socket and ID:

var userSocket = connectedSockets[data.recipientID].usersocket;
TypeError: Cannot read property 'usersocket' of undefined

I am connecting both clients and both ID's are saved in connectedSockets but I am still getting the undefined error.

Any idea why that is?

Additionally, I was wondering if I am understanding this right. When wanting to send a message to a specific client I am using the socket object received when a client is connecting and the socketID assigned to the client to emit my message with this command:

io.sockets.userSocket[socketID].emit(recipient, {Message: data.Message});

Is this the right approach on using private messaging in socketIO?

0

There are 0 best solutions below