Search code examples
node.jsmongodbsocket.iochatreal-time

Socket.io Private messaging, with multiple users online at the same time


So I am building, a chat app and need help figuring out how to send private messages. This is the code I have, to 'send a message'.

    users = {}

    socket.on('send message', function(data, callback){
    var msg = data.trim();
    console.log(users);
    console.log('after trimming message is: ' + msg);

    var name = req.params.posteruname;//reciever
    var msg = msg;
    if(name in users){

      var message = new Chat({
            msg : msg,
            sender : req.user.username,
            reciever : name
      }).save(function(err, savedMessage){
        if(err) {
          users[name].emit('whisper', {msg: "Error, some tried sending you a message but something went wrong", nick: socket.nickname});
        } else {
            users[name].emit('whisper', {
            reciever: name,
            sender:req.user.username,
            msg:msg
              });
            }
    });

    } else{
      callback("Something went wrong");
    }


    });

This code isn't working very well. When I try to send message, it still displays to all users.


Solution

  • Take a look in this document. You should specify rooms. Every one will be a "room", when you send a message with event and room specified the correct user will receive it.

    Your users object is just a plain object, don't reflect what I'm talking about.