【问题标题】:(Node js) How to send notification to specific user?(Node js)如何向特定用户发送通知?
【发布时间】:2016-04-11 15:28:57
【问题描述】:

我有服务器代码 server.js

var socket  = require( 'socket.io' );
var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = socket.listen( server );
var port    = process.env.PORT || 3000;
var nik = {};

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});


io.on('connection', function (socket) {
    socket.on( 'new_count_message', function( data ) {
        io.sockets.emit( 'new_count_message', {
            new_count_message: data.new_count_message
        });
    });

    socket.on( 'update_count_message', function( data ) {
        io.sockets.emit( 'update_count_message', {
            update_count_message: data.update_count_message
        });
    });

});

这就是我使用它的方式

$.ajax({
            type: "POST",
            url: "(some_url)",
            data: $("id_form").serialize(),
            dataType: "json",
            beforeSend:function(){
                alert('bla..bla..');
            },
            success: function (result) {
                if (result.status) {
                    var socket = io.connect('http://' + window.location.hostname + ':3000');
                    socket.emit('new_count_message', {
                        new_count_message: result.new_count_message
                    });
                } else if (result.status == false) {
                    alert(error);
                    return false;
                }
            },
            error: function(xhr, Status, error) {
                alert(error);
            }
        });

该功能运行良好,但它发送给所有人。如何向特定用户发送通知?我有我要发送通知的 ID 用户

谢谢

【问题讨论】:

    标签: javascript ajax node.js sockets socket.io


    【解决方案1】:

    嗯,

    • 使用io.sockets.emit 可以向所有套接字发送消息。请改用io.sockets.in("roomname").emit("message")
    • 如果您有要发送消息的套接字 ID,您可以使用 io.sockets.connected["socketid"].emit("message")
    • 如果您在 io.on('connection') 函数内,并且想向同一个套接字发送消息,则只需使用 socket.emit

    另一种方式是:

    • 当新的socket连接时,将此socket添加到特定房间socket.join("UniqueUserId")socket.join("UniqueUserSessionId")...然后使用第一个选项io.sockets.in("UniqueUserId").emit("message")io.sockets.in("UniqueUserSessionId").emit("message")

    例子:

    io.on('connection', function (socket) {
    
        //get the unique socket socketId on connection
        var socketId = socket.id;
        //you can add this socket id to a Database to use it later, etc...
    
        //use sessionStore like Redis or memStore to get a unique sessionId
    
        //as well you can extract a cookie with the UserId (you need to secure this to be sure that the user not modified the cookie) (you can use 2 cookies 1 for the userid other for the encrypted password and check if the cookies data is the same than in your users Database) etc etc etc. User Session is a lot better). Read about nodejs session store and socket session. Something like...
        var cookies = qs.parse(socket.handshake.headers.cookie, "; ");
        var user_id = cookies.user_id; //or some other cookie name;
        socket.join(user_id);
    
        socket.on( 'new_count_message', function( data ) {
    
            //all sockets
            io.sockets.emit( 'new_count_message', {
                new_count_message: data.new_count_message
            });
    
            //same Socket
            socket.emit( 'new_count_message', {
                new_count_message: data.new_count_message
            });
    
            //specific Socket by SocketId
            //io.sockets.connected["socketid"].emit( 'new_count_message', {
            io.sockets.connected[socketId].emit( 'new_count_message', {
                new_count_message: data.new_count_message
            });
    
            //all sockets in a specific Room
            //io.sockets.in("roomname").emit( 'new_count_message', {
            io.sockets.in(user_id).emit( 'new_count_message', {
                new_count_message: data.new_count_message
            });
    
        });
    
    });
    

    【讨论】:

    • 感谢您的回复,我必须把这个放在哪里? io.sockets.connected["socketid"].emit("message")。基本上,这不适用于房间/聊天,我想向特定用户发送通知(通过选择,以便始终为 1):)
    • @ChandraPutraWijaya 添加了示例。
    • 谢谢,有点知道。但是,当我尝试使用 socket.join() 时,显示错误。 socket.join 不是函数
    • @nada 我对 socket-io 有点陌生。每个用户的套接字 ID 是否唯一且不可变?
    • @MostafaGhadimi 我不知道它是否是不可变的(也许你可以将它重新分配给一个新值)但 socketId 'per se' 应该是唯一的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    相关资源
    最近更新 更多