1

So here is the situation, I need to create a room for two people that exist in our database. The problem is that I can't identify with those users based on their sockets.

Let's say there are two random users user1 and user2. Now, user1 wants to initiate chat with user2, so I need to create a room when the user1 initiates and join the two users to that room. Here's the problem that sockets join a room, and socket.id changes with reconnection from the same host. So, I can't figure out how do I join user2 to the room.

Here's the code.

export default function(socketio) {

  let sockets = [];
  let people = {};

  const findUserById = function findUserById(data) {
    for (let x in people) {
      if (people[x].userId === data) {
        return x;
      }
    }
  }

  /**
   * [createRoom Creates a room for two users]
   * @param  {[type]} data1 [Mongoose objectId for user]
   * @param  {[type]} data2 [Mongoose objectId for user]
   * @return {[type]}       [A string of 6 characters that identifies with the room]
   */
  const createRoom = function createRoom(data1, data2) {
    const user1 = data1.toString().slice(-3);
    const user2 = data2.toString().slice(-3);

    return user1 + user2;
  }


  socketio.on('connection', function(socket) {
    console.log(`Connection made from ${socket.id}`);

    sockets.push({
      socket: socket,
      id: socket.id
    });

    socketio.on('join', (data) => {
      people[socket.id] = {
        userId: data
      }
    })

    socketio.on('initiate', (data) => {
      const receiverSocket = findUserById(data.receiver);
      if (receiverSocket) {
        let room = createRoom(people[socket.id].userId, receiverSocket.userId)

        let chat = new Chat({
          room: room
        });

        /*
          Now, we'll add the chats to the respective users.
        */

        User.findById(people[socket.id].userId, (err, foundUser) => {
          foundUser.chats.push({
            room: room,
            partner: receiverSocket.userId
          })

          foundUser.save((err, success) => {
            if (!err || success) {
              User.findById(receiverSocket.userId, (err, secondUser) => {
                secondUser.chats.push({
                  room: room,
                  partner: people[socket.id].userId
                })

                secondUser.save()
              })
            }
          })
        })

        let user1Socket = sockets.filter((el) => {
          return el.id === socket.id
        })

        let user2Socket = sockets.filter((el) => {
          return el.id === receiverSocket
        })
        user1Socket.socket.join(room);
        user2Socket.socket.join(room);

        socketio.sockets.in(room).emit('private room created', {
          room: room
        });
      }
    })

    socketio.on('job', (data) => {
      socketio.broadcast.emit('jobPosted', data);
    })

    socketio.on('message', (data) => {
      Chat.findOne({room: data.room})
          .then((data)=>{
            data.chat.push({'content': data.message, 'userId': data.sender, 'date': new Date()})
            data.save()
                .then((success)=>{
                    socketio.sockets.in(data.room).emit('messageReceived', data.message)      
                })
          })
    })

  });
}

The logic here was that each time a connection is made I would store that socket.id and later on pull it out to create a room. But this fails when socket.id changes.

Can anyone help me with this?

relentless-coder
  • 1,478
  • 3
  • 20
  • 39
  • You shouldn't rely on socket id and use some other unique user identifier. Use that unique identifier of each user while connecting through socket.io client. – Jyotman Singh Jul 27 '17 at 06:32
  • Can you explain upon that? According to my understanding, connections take place through sockets, how do I introduce unique id? – relentless-coder Jul 27 '17 at 06:35
  • See [this](https://stackoverflow.com/a/36821359/4440874) answer to understand how you can implement authentication in socket.io server to identify clients. – Jyotman Singh Jul 27 '17 at 06:54
  • No. You didn't understand the situation. I somehow need to keep a track of the users with their sockets, so that when a user initiates chat with another user, I can create a room with those two users and join them to that room – relentless-coder Jul 27 '17 at 07:04
  • Yes exactly so the first step to that would be identifying who the user is when a new socket connection is made. When you identify the user, you will get the user's unique id. Then you can check whether an existing chat for that user id exists or not. Socket id may change on every connection but the user id will never change. – Jyotman Singh Jul 27 '17 at 07:40
  • No. No. I am talking about room. I have to create a room. In order to send the message to the correct room, I need to join the two users to the room. And the room is created whenever a user initiates chat with another user. And for sockets room to work, I need both users sockets and join them to a room. – relentless-coder Jul 27 '17 at 07:44
  • 1
    Sorry mate I guess I'm not able to fully understand the problem due to my lack of experience with socket.io. I'll upvote your question. – Jyotman Singh Jul 27 '17 at 07:50
  • @relentless-coder did you get the solution to this problem? – Akash Soni Apr 28 '20 at 08:14

0 Answers0