如何识别连接到套接字的两个用户,并将它们加入到一个房间? Socket.io

时间:2017-07-27 05:39:56

标签: node.js sockets socket.io

所以情况就是这样,我需要为我们数据库中存在的两个人创建一个房间。问题是我无法根据他们的套接字与这些用户进行识别。

假设有两个随机用户user1和user2。现在,user1想要启动与user2的聊天,因此我需要在user1启动并将两个用户加入该房间时创建一个房间。这是套接字加入房间的问题,而socket.id随着从同一主机重新连接而改变。所以,我无法弄清楚如何将user2加入房间。

这是代码。

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)      
                })
          })
    })

  });
}

这里的逻辑是,每次建立连接时,我都会存储socket.id,然后将其拉出来创建一个房间。但是当socket.id发生变化时,这会失败。

任何人都可以帮我吗?

0 个答案:

没有答案