2013-10-10 52 views
1

我一直在使用nodeJs动态创建socket.io上的房间,并在我的问题上搜索了两天。当我创建一个房间到服务器上,我提出这样的: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

参见[Socket.io broadcast.to和sockets.in间客房区别] [1] [1] :http://stackoverflow.com/questions/6873607/socket-io-rooms-difference-between-broadcast-to-and-sockets-in –

+0

代码看起来不错,也许,检查** data.room **。 –

回答

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 */ 
    }); 

我猜你需要的是​​

+0

坦克的这个答案。我的问题是我在我身边的一个错误。我的代码和io.sockets.in(data.room).emit('recieve',data.message)帮助发现错误,现在我连续使用socket.broadcast.to(data.room).emit('recieve',data.message)没有任何问题。socket.io的代码是good.tank的所有 – yanstv