2013-10-10 5 views
1

nodejs를 사용하여 socket.io에서 동적으로 방을 생성하기 위해 2 일 동안 제 문제를 찾았습니다. 내가 서버에 방을 만들 때, 나는 이런 식으로합니다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 */ 
    }); 

난 당신이 필요로하는 무슨 생각 io.sockets.in

+0

탱크의 답변입니다. 내 문제는 저의 실수였습니다. io.sockets.in (data.room) .emit ('recieve', data.message)는 코드에서 버그를 발견하는 데 도움이되었습니다. 아무 문제없이 socket.broadcast.to (data.room) .emit ('recieve', data.message)를 계속 사용하십시오. socket.io의 코드는 좋았습니다. – yanstv