javascript - 如何让 2 个用户加入 socket.io 中的同一个房间进行 1 对 1 聊天?
问题描述
我在这里查看答案How to send a message to a specific client with socket.io,特别是第二个,它建议使用房间进行 1 对 1 聊天。我在我的服务器上做了以下事情:
io.on('connection', (socket) => {
socket.on('message', (data) => {
socket.join(data.to);
io.sockets.in(data.to).emit('send_message', { message: data.message, to: data.to });
});
});
在我的客户上,我有这个:
const sendMessage = (e) => {
e.preventDefault();
io.emit('message', { to: friend._id, from: currentUserID, message }); // here friend._id
// will be currentUserID in the 2nd user's browser. Which makes it so they join different rooms
setMessage('');
}; // this function runs on form submission.
io.on('send_message', (message) => {
// do stuff with the message
});
但是我的用户不会加入同一个房间。每个人都加入一个由其他用户的 id (friend._id) 标识的房间。所以他们无法看到彼此的消息。在上面的答案中,他们做了类似的事情,只是使用每个用户的电子邮件,据我所知,这应该会导致我遇到的相同问题。
解决方案
推荐阅读
- html - 造型亚马逊附属链接
- javascript - 出现错误无法解构'window.location'的属性'protocol',因为它在构建它时在nextjs应用程序中未定义
- python - 如何在数据框中找到关于另一列值条件的列的最大总和?
- python - 为什么head()方法分组后显示的记录多于默认的5条记录?
- tinymce - 任何想法如何摆脱打印光标,完全卡住
- css - 如何在具有不同内容长度和不同高度的自定义组件中滑动
- flutter - Flutter:如何在一个图标中实现两条路由
- kdb - Q中的API请求
- excel - 带有 2 个 AND 参数的 EXCEL COUNTIF
- android - Android 简单列表与 AsyncTask 替代