Socket io group chat logic #5132
Answered
by
darrachequesne
emirhanyagci
asked this question in
Q&A
-
I'm building a chat app and i'm comfused at some point how should be socket io logic these are my things please share if there is a more optimal option 1-) The new message events are emit for all user kinda like that users.forEach((user) => {
if (user._id == newMessageRecieve.sender._id) return;
socket.in(user._id).emit('message recieved', newMessageRecieve);
}); 2-) The other option is emiting to chatId but in this case i need add user to all existing chat. this is the situation i'm open the all advice. |
Beta Was this translation helpful? Give feedback.
Answered by
darrachequesne
Jul 16, 2024
Replies: 1 comment 3 replies
-
Hi! You can take a look at our chat platform project. In this project, we use your 2nd option:
io.use(async (socket, next) => {
// [...]
let channels;
try {
channels = await db.fetchUserChannels(socket.userId);
} catch (e) {
return next(new Error("something went wrong"));
}
channels.forEach((channelId) => {
socket.join(channelRoom(channelId));
});
// [...]
next();
});
socket.broadcast
.to(channelRoom(message.channelId))
.emit("message:sent", message); |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
emirhanyagci
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi!
You can take a look at our chat platform project. In this project, we use your 2nd option:
Source: https://github.com/socketio/socket.io-chat-platform/blob/2a32486ff621a61648a3b28fad751e94a6cf2304/server/src/index.js#L92-L94