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.

Hitesh Chandwani
  • 159
  • 1
  • 1
  • 14

1 Answers1

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)
});
pedrommuller
  • 15,741
  • 10
  • 76
  • 126