简体   繁体   English

使用node.js + socket.io发送通知

[英]Sending notification using node.js + socket.io

I am trying to send notification using Node.js + soket.io 我正在尝试使用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. 如果我在发出“发送到服务器”期间通过了自己的user_id,则返回给自己,但是如果使用其他user_id(已在其他浏览器中登录),则不会向该用户发送任何内容。

Please point how i can send notification to different user when some action occur. 请指出发生某些操作时如何将通知发送给其他用户。

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) 仅针对特定用户(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: 无需在客户端将ID与您的侦听器的名称连接在一起:

socket.on('notification',function(data){
    alert(data)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM