Reputation: 1074
I don't know if it's a bug or if I'm doing something wrong but if i broadcast more than one message, only the first message is broadcasted to the right room, all others are broadcasted to everyone connected to the socket.io.
socket.on('clientMessage', function(content){
socket.emit('serverMessage', {name : 'You said', data : content} );
socket.get('username', function(err, username){
if (err) { throw err; }
if(! username){
username = socket.id;
}
socket.get('room', function(err, room){
if (err) { throw err; }
if(room) {
socket.broadcast.to(room);
}
socket.broadcast.emit('serverMessage', {name: username, data : content} );
socket.broadcast.emit('serverMessage', 'test' );
});
});
});
My problem is at theses lines :
socket.broadcast.emit('serverMessage', {name: username, data : content} );
socket.broadcast.emit('serverMessage', 'test' );
With two socket.broadcast.emit, the second is broadcasted to everyone.
How comes that ???
Upvotes: 0
Views: 978
Reputation: 24958
You're making the incorrect (though understandable) assumption that socket.broadcast.to(room)
makes a lasting change to the internal state of the socket connection, so that any subsequent broadcasts are made to the specified room. In reality, it only lasts for one emit
before being reset. The to
method is meant to be chained to each emit
call, like so:
socket.broadcast.to(room).emit('serverMessage', {name: username, data : content});
socket.broadcast.to(room).emit('serverMessage', 'test' );
By default, every socket is joined to a room with an empty name, so if your intention is to broadcast to a specific room if it exists, and otherwise broadcast to everyone, then your code can be rewritten simply as:
socket.get('room', function(err, room){
if (err) { throw err; }
// Default to the global room
room = room || '';
socket.broadcast.to(room).emit('serverMessage', {name: username, data : content} );
socket.broadcast.to(room).emit('serverMessage', 'test' );
});
Upvotes: 1