your text
io.on(“connection”, (socket) => {
your text
console.log(“Connected to socket.io”);
socket.on("setup", (userData) => {
socket.join(userData._id);
socket.emit("connected");
});
socket.on("join chat", (room) => {
socket.join(room);
console.log("User Joined Room: " + room);
});
socket.on("typing", (room) => socket.in(room).emit("typing"));
socket.on("stop typing", (room) => socket.in(room).emit("stop typing"));
socket.on("new message", (newMessageRecieved) => {
var chat = newMessageRecieved.chat;
if (!chat.users) return console.log("chat.users not defined");
chat.users.forEach((user) => {
if (user._id == newMessageRecieved.sender._id) return;
socket.in(user._id).emit("message recieved", newMessageRecieved);
});
});
});
my question is alice logged in “setup” event triggers and alice is added to a private room having roomId as her userId (lets say 123) and when alice clicks on some chat “join chat” triggers and alice is added to another room having room id as ChatId (chatIdd represents the ID od that particular chat model)….now when alice tries to send message lets say to a single user or group depending on the chat she clicked on….”new message” event triggers gets access to users array and sends message to the users with the array except the sender using the “UserID” which will give access to the private room created by “setup” event …so if there are 3 users i.e it is a group chat messages will be sent to them and displayed on the UI …but then what was the need to create “join chat” event because we are sending messages based on userId room which is created in “setup” and not ‘join chat” …but if i comment “join chat” messages are not sent in real time…then i need to reload the server can anyyone explain me the code and flow..
Bhavnesh Bhat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.