2

I am trying to send notification using Node.js + soket.io

On client side i emit to server to listen

socket.emit('send to server',{user_id:user_id,other_stuff:other_stuff})

On node

socket.on('send to server',function(date){ socket.emit('notification_'+user_id,'test data'); });

On client side to listen notification

socket.on("notification_<?php echo $_SESSION['user_id'];?>",function(date){alert(data)});

Problem is that it doesn't send notification to other user

If i pass my own user_id during emit "send to server" then it returns to myself but if use other user_id (who is logged in other borwser) it doesn't send anything to that user.

Please point how i can send notification to different user when some action occur.

1 Answer 1

5

In case you want to send a notification to other users under the same namespace:

socket.on('send to server',function(data){ 
        socket.broadcast('notification','test data'); 
    })

only for a specific user (sockets.io 1.x)

socket.on('send to server',function(data){ 
    socketId =  getSocketIdFromUserId(user_id);
    io.to(socketId).emit('notification', 'test data');
 })

there's no need to join the id with the name of your listener on the client side:

socket.on('notification',function(data){
    alert(data)
});
6
  • Hello Jack, thanks a lot for your answer, just had one little doubt, when i will use io.to(data.user_id), who node will identify which user to send Oct 27, 2014 at 22:06
  • my mistake is the socketId that you'll need to pass Oct 27, 2014 at 22:11
  • you probably will need to do a map between the socketId and the userId, take a look to this answer stackoverflow.com/questions/6563885/… Oct 27, 2014 at 22:14
  • Jack can you help me out with one more problem Oct 31, 2014 at 21:03
  • Sure open another question and tag me Oct 31, 2014 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.