0

I've Implemented Node.js server side, and ios client side for sending pm message . But main issue , my code still acts like text message is broadcasting for all clients. ( I've tried on 3 phone, I just send e message to specific client , but message gone both clients and also mine phone which i sent that message )

My server code looks like that :

io.sockets.on('connection', function (socket) {
  var userName;
  var userSrcID;

  socket.on('setUserName',function(user){
    userName = user.name;
    userSrcID = user.id;
    clients[user.name] = socket;
    clients[user.id] = socket;
    console.log('data = ',user);
    //io.sockets.emit('new user', user.name + " has joined.");
  });

  socket.on('message', function(msg){
    io.sockets.emit('message', msg);
  });

  socket.on('pm', function(msg){
    fromMsg = {from:userSrcID, txt:msg}
    //clients[msg.to].emit('private message', fromMsg);
    console.log('Gidicek username:',userName);
    io.sockets.emit('new message',{msg: msg,destID:userSrcID}); 

I can build a condition that if that message's destionation user id is not belong my user id, do not show me but it will more like using Old-School HUB Network instead of switch :)

Any help will be appreciated

Best Regards ,

Onder OZCAN
  • 1,496
  • 1
  • 16
  • 33
  • If you want to send to a specific user, you need to send only to that user's socket. see: Second answer in [Send message to specific client with socket.io and node.js](http://stackoverflow.com/questions/4647348/send-message-to-specific-client-with-socket-io-and-node-js) – dc5 Aug 14 '13 at 14:44
  • I am keeping userid that client pushes to node as destination id , which is = clients[user.id] = socket; So how can i send that user with using that declaration ? – Onder OZCAN Aug 14 '13 at 14:51
  • `clients[userDestId].emit(…)` – dc5 Aug 14 '13 at 14:57
  • thank you :) it worked... – Onder OZCAN Aug 14 '13 at 22:00

2 Answers2

0

Do not use io.sockets.emit, but use the socket you stored in the clients array.

When you want to send to a specific user, you should pass the username or -id, with the message, like so:

socket.on('pm', function(message) {
    var to = msg.toUserId;
    var msg = message.message;
    clients[to].emit(msg);
}

From within the client:

socket.emit('pm', {'toUserId': userid, 'message': 'hello over there'});
Kurt Pattyn
  • 2,674
  • 2
  • 28
  • 39
0

You could send message as an object, so you could include receiver user ID with it. having that you could retrieve receiver socket and then emit a message to that particular user.

It would look something like this.

// assuming msg object would look something like this
// msg = { text: 'message text', receiverID: 123 };  

socket.on('pm', function(msg){
    var userSocket = clients[msg.receiverID];
    userSocket.emit('new message',{msg: msg.text, destID:userSrcID}); 
});
Giedrius
  • 1,364
  • 3
  • 14
  • 27