Socket IO - 将消息附加到正确的位置

问题描述 投票:0回答:1

我正在创建一个实时聊天应用程序,用户可以在其中与其他用户实时聊天。所有用户都存储在我的 MongoDB 数据库中。我在前端使用 React,在后端使用 Node 和express。

当用户连接到套接字服务器时,它们会被添加到服务器上存储的用户数组中,如下所示:

var users = [
   // User objects
   {username: test1, id: 32d2, socketId: ue3e9393kd3},
   {username: test2, id: 322, socketId: ude3e339393kd3},
   {username: test3, id: 333dw2, socketId: ud33e9393kd3},
]

在前端,当与用户聊天时,他们首先从消息列表中选择其他用户名,然后重定向到路线

chat/otheruserid
。因此,无论他们想与什么用户聊天,其他用户的 ID 都会存储在 url 中。

提交消息发送时,服务器接收并发送回客户端。我目前使用以下代码来发送消息事件。

io.to(user.socketId).emit('send message', msg)

此套接字 ID 将通过过滤用户数组来查找特定用户(即他们在前端选择与之聊天的用户)来获得

我遇到的问题是,如果使用上面的示例,如果用户 test1test2 聊天,并与 test3 聊天,如果 test2test3 都向用户 发送了消息test1,我如何才能将消息附加到正确聊天屏幕的 DOM 中。

例如,如果 test2test3 大约在同一时间向 test1 发送消息,并且 test1test2 位于聊天页面,那么您可以将来自 test2 的消息附加到当前页面的 DOM。但是,如果在带有 test2 的聊天页面上,并且 test3 发送消息,我如何将消息从 test3 附加到位于路径:

chat/test3id
的聊天屏幕,所以当用户最终转到这条路径下,新消息已经追加到dom了吗?谢谢。

javascript node.js socket.io
1个回答
0
投票

@Sam 我认为,您需要一种方法将传入的消息与前端正确的聊天屏幕相关联。一种好的方法是在从服务器向客户端发送消息时使用目标用户的 ID。

我可以向您展示一个简化的示例。

  • 服务器端
// Assuming user is the sender and targetUserId is the id of the user they are chatting with
io.to(targetUserSocketId).emit('send message', { senderId: user.id, message: msg });
  • 客户端
// Assume you have a state variable to keep track of the currently open chat screen
const [currentChatUserId, setCurrentChatUserId] = useState(null);

// Handle the 'send message' event
socket.on('send message', ({ senderId, message }) => {
  if (senderId === currentChatUserId) {
    // Append the message to the DOM of the currently open chat screen
    // You can use your own logic to update the chat messages in the state
    // or trigger a re-fetch of messages for the open chat screen
  } else {
    // Store the message for later use (e.g., in a Redux store or component state)
    // This way, when the user navigates to the chat screen with the senderId,
    // you can retrieve and display the stored messages
  }
});

// Update the currentChatUserId when the user navigates to a different chat screen
const handleChatNavigation = (userId) => {
  setCurrentChatUserId(userId);
  // Fetch messages for the selected chat screen or load stored messages
};

希望对您的理解有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.