(节点js)如何向特定用户发送通知?

时间:2016-01-07 09:40:20

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

我有服务器代码 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);
            }
        });

该功能完美运行,但它发送给所有人。如何将notif发送给特定用户?我有ID用户,我想发送通知

由于

1 个答案:

答案 0 :(得分:3)

那么,

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

另一种方式是:

  • 当新套接字连接时,将此套接字添加到特定会议室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
        });

    });

});