PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 5, 2022

[FIXED] How to handle concurrent request with socket io while joining room

 August 05, 2022     express, mongodb, mongoose, node.js, socket.io     No comments   

Issue

I'm trying to create/join a room with limit of 2 user per room everything is working fine but when 2 users make a concurrent request to create/join a room all 3 users are added to same room. i have tried using

  1. simple mongodb insert/update
  2. using transaction
  3. now storing in memory

    here is the code
const rooms = {};
module.exports = function ({ io, socket }) {
  socket.on("/createJoinPublicRequest", async ({ user }) => {
    let title = `${user._id}.${Date.now()}`;
    let foundRoom = Object.keys(rooms).find((room) => {
      return rooms[room].roomLimit > rooms[room].users.length;
    });

    if (!foundRoom) {
      //create a room if not found
      rooms[title] = {
        title,
        users: [
          {
            _id: user._id,
          },
        ],
        roomLimit: 2,
        roomType: "public",
        status: "open",
      };
      socket.join(title);
    } else {
      // join existing room
      room = rooms[foundRoom];
      room.users.push({ _id: user._id });
      if (room.users.length == room.roomLimit) {
        room.status = "full";
        if (await storeToMongoDB(room)) {
          delete rooms[foundRoom];
        }
      }
      socket.join(room.title);
    }

    await User.findByIdAndUpdate(user, {
      joinedRoom: title,
    });

    return;
  });

Solution

you should use mutex lock to prevent adding more Users to Room.

For Single Instance : https://www.npmjs.com/package/async-mutex

For Multi Instance : Redis Mutex Lock



Answered By - Chintan Patel
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing