socket.io创builddynamic空间
我一直在我的问题谷歌2天dynamic创buildsocket.io使用nodeJs的房间。 当我创build一个服务器的空间,我这样做:
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); });
所有的用户收到消息。 为什么房间不适合我? 我认为代码是好的!
坦克
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