socket.io add user to room manually (node.js)
Asked Answered
D

2

9

I have a chat application which is working privately.My implementation is :

1-A user come to another user profile page and write a message. After this I am creating a room for this conversation.

socket.join(data.user);

2-Receiver user will take this message (only this user) but I don't know how can I join this receiver user to this room. So it is my question basically. I need to add "MANUALLY" this receiver user to my room. In this way when I broadcast message to this room, message will be emit this two user (one is anonymous,the other is registered user). It will provide some of my code.

server
.on('connection', function(socket) {

    server.to(socket.id).emit('yourSocketId',{ socketid : socket.id,connectedDate : Date.now });

    socket.on('AnonymousMessage', function(data) {
        if(data.isanon == true) 
        {
            socket.join(data.user);

            server.to(data.user).emit('AnonymousBroadcast', {
                message: data.message,
                user: data.user,
                isanon : data.isanon,
                date : data.date,
                tabno : data.tabno
            });
        }
        else
        {
            socket.join(****); //-- I need add manually here this registered user to anonymous user room
            server.to(**anonymousroomname**).emit('AnonymousBroadcast', {
                message: data.message,
                user: data.user,
                isanon : data.isanon,
                date : data.date,
                tabno : data.tabno
            });
        }

    });

});

Any suggestion will be great for me. Thanks.

Digestant answered 25/3, 2015 at 13:55 Comment(0)
A
11

Those very private rooms you mention in your question are probably the correct way of doing this. You need to hold references to your users and their respective sockets though. Then, once an anonymous - or any other for that matter - user sends a private message to a registered user, simply join both of them to the same room.

var io = require('socket.io')(http);
sockets = [];
people = {};

io.on('connection', function (socket) {
    sockets.push(socket);

    //join the server
    io.on('join', function(name){
      people[socket.id] = {name: name};
    })

    //disconnect from the server
    io.on('disconnect', function(){
      delete people[socket.id];
      sockets.splice(sockets.indexOf(socket), 1);
    });

    //initiate private message
    io.on('initiate private message',function(receiverName, message){
      var receiverSocketId = findUserById(receiverName);
      if(receiverSocketId){
        var receiver = people[receiverSocketId];
        var room = getARoom(people[socket.id], receiver);

        //join the anonymous user
        socket.join(room);
        //join the registered user 
        sockets[receiverSocketId].join(room);

        //notify the client of this
        io.sockets.in(room).emit('private room created', room, message);

        //
      }
    });

    io.on('send private message', function(room, message){
      io.sockets.in(room).emit('private chat message', message);
    });
  }

//you could use e.g. underscore to achieve this (
function findUserByName(name){
  for(socketId in people){
    if(people[socketId].name === name){
      return socketId;
    }
  }
  return false;
}

//generate private room name for two users
function getARoom(user1, user2){
  return 'privateRooom' + user1.name + "And" + user2.name;
}

This is, of course, a very naive and incomplete solution! Users need to have ids and so do rooms, you need to check for existing user names, you will also very likely need to hold references to rooms etc. but you get the gist, right?

An alternative would be using whispers - you can send a message to just one socket=person using the following: io.sockets.socket(receiverSocketId).emit("whisper", message, extraInfo);. I would advise against that though since it entails having to implement whispers going back and forth which could get rather messy.

Aalborg answered 31/3, 2015 at 9:29 Comment(2)
sorry for late reply. I will just try out your solution and I will write comment. Thanks also.Digestant
Hi @Tadeas I tried your solution and I got this error ** Cannot call method 'join' of undefined ** .This line is sockets[receiverSocketId].join(room);. Why is giving error ? Its looking so logical.Digestant
C
0

The socketids you are trying may not be connected. You can use the below while trying to join rooms

io.sockets.connected[receiverSocketId].join(room);
Chardin answered 24/5, 2020 at 7:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.