2013-10-10 50 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