我一直在谷歌搜索我的问题2天,使用nodeJs在socket.io上动态创建房间。当我为服务器创建一个房间时,我这样做:
socket.on('follow_me', function (user_id) { //I use the user_id of the user to create room
socket.join(user_id);
console.log(server.sockets.manager.rooms);
});
如果接下来,我想通过
向所有连接的人发送消息socket.join(user_id);
当我使用时:
socket.on('message', function (data) {
socket.broadcast.to(data.room).emit('recieve',data.message); //emit to 'room' except this socket
});
此会议室中的其他用户未收到该消息;但如果我使用:
socket.join(user_id);`,when i use :
socket.on('message', function (data) {
socket.broadcast.emit('recieve',data.message);
});
所有用户都会收到该消息。为什么房间对我不起作用?我认为代码很好!
坦克的
答案 0 :(得分:1)
socket.on('message', function (data) {
/*considering data.room is the correct room name you want to send message to */
io.sockets.in(data.room).emit('recieve', data.message) //will send event to everybody in the room while
socket.broadcast.to(data.room).emit('recieve', data.message) //will broadcast to all sockets in the given room, except to the socket which called it
/* Also socket.broadcast.emit will send to every connected socket except to socket which called it */
});
我猜你需要的是io.sockets.in