Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

better approach for one to one and group chat nodejs Socket.io

I am implementing one to one and group chat in my application in NodeJs using socket.io and angular 4 on client side. I am new to socket.io and angular 4.I want to ask what is better approach for this e.g if user want to send a message to specific user or it want to send a message to group of users.

According to my Rnd should I keep the obj of all connected users and that obj contain the socket id of that user with his user name (email or what ever ) so that if some user want to send message to some one we should need his user name and we can access his id through his user name . Or is there any solution except this ? And where should i keep that obj of user and socket id global variable or database ?

like image 579
Asad Avatar asked Oct 23 '17 14:10

Asad


1 Answers

One-to-one and group chat is very similar. If we use rooms in socket.io https://socket.io/docs/rooms-and-namespaces/#.

In one-to-one only 2 users are in the same room. where as in a group chat more than 2 people can be in the same room.

So when a person sends a mesage, they send it to the room they belong to and want to chat with instead of sending it to individual users. Then, everyone in that room, whether its one other person or multiple people will receive it.

- Node.js

Join a client to a room

io.on('connection', function(client){
     client.join(conversation._id)
});

Emitting a message to a room

   client.broadcast.to(conversation_id).emit('message:send:response', {
       msg: res.msg,
       conversation_id: res.data._id
  });

- Angular

Listen to emitted messages

getMessages(conversation_id) {

    let observable = new Observable(observer => {

        this.socket.on('message:send:response', (chat) => {

            if (chat.conversation_id === conversation_id) {
                observer.next(chat.msg);
            }
        })

    });

    return observable;

}
like image 132
Kay Avatar answered Sep 23 '22 08:09

Kay