Ideal way to handle multiple socket rooms?

Issue

So I am creating a chat application and I want to handle multiple chat rooms. Now I watched some tutorials and came up with a way.

const io = require("socket.io")(http);
io.on("connection", (socket) => {
    socket.on("joinRoom", (roomid) => {
        //Joining the room
        socket.join(roomid)
        //Broadcasting all previous messages
        io.to(roomid).emit("messages",allPreviousMessages)
    })
    socket.on("chatMessage", (data) => {
        //Saving msg to dB then broadcasting
        io.to(roomid).emit("message",receivedMessage)
    })
    socket.on("disconnect",(data) => {
        //updating user's lastSeen info in dB
    })
})

So on my frontend when user clicks on a chatroom we call the "joinRoom" event and connect to the room and on clicking another chatroom make the same process of joining room.
Is this an ideal way for handling multiple chatrooms? If not so please let me know a better solution.

Solution

I think the best way to implement private rooms or channels or chats is this way. I have implemented an example for these three sections. Link

Answered By – Ali Azmoodeh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published