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 ?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With