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