Home > Software engineering >  Ideal way to handle multiple socket rooms?
Ideal way to handle multiple socket rooms?

Time:08-21

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.

CodePudding user response:

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

  • Related