首页 > 解决方案 > 如何让 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) 标识的房间。所以他们无法看到彼此的消息。在上面的答案中,他们做了类似的事情,只是使用每个用户的电子邮件,据我所知,这应该会导致我遇到的相同问题。

标签: javascriptsocketswebsocketsocket.io

解决方案


推荐阅读