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)
});
Sign up to request clarification or add additional context in comments.

6 Comments

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
my mistake is the socketId that you'll need to pass
you probably will need to do a map between the socketId and the userId, take a look to this answer stackoverflow.com/questions/6563885/…
Jack can you help me out with one more problem
Sure open another question and tag me
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.