我正在使用Socket.IO和Express创建聊天,以便能够一对一聊天(私人聊天)。
主要问题是:我想向socket.id发送私人消息,但我希望发件人收到与发送给接收者相同的消息。
module.exports = (io, socket) => {
socket.on('send private message', async (msg) => {
const emitterUser = // mongoose query to get the emitter
const receiverUser = // mongoose query to get the receiver
// sending to individual socketid (private message)
socket.to(receiverUser.socketId).emit('receiver private message', msg); // <- sending to the receiver
socket.emit('sender private message', msg);// <- sending to the sender
});
}
我想知道是否有更好的方法来创建私人聊天,或者我走错了方向。
答案 0 :(得分:-1)
您可以使用socket-io的GROUP功能 docs:https://socket.io/docs/server-api/
更新
io.on('connection', function(socket){
console.log('people connect: ' + socket.id);
// listen create and join room from client
socket.on('create-room', function(nameroom){
socket.join(nameroom); // if room not exists create and join to room, if room exists client will join to room
console.log(nameroom);
// get all name room
var array=[];
for(r in socket.adapter.rooms){
array.push(r);
}
console.log(array);
});
// listen message from client
socket.on('client-send-message', function(message){
io.sockets.in('some-name-room').emit('key-chat', message);
});
});