Node.js was something I was really interested forawhile and I used it in one of my project to make a multiplayer game.
io.sockets.in().emit()
and socket.broadcast.to().emit()
are the main two emit methods we use in Socket.io's Rooms (https://github.com/LearnBoost/socket.io/wiki/Rooms) Rooms allow simple partitioning of the connected clients. This allows events to be emitted with to subsets of the connected client list, and gives a simple method of managing them.
They allow us to manage the subsets of the connected client list(which we call rooms) and have the similiar functionalities like the main socket.io functions io.sockets.emit()
and socket.broadcast.emit()
.
Anyway I'll try to give the example codes with the comments to explain. See if it helps;
Socket.io Rooms
i) io.sockets.in().emit();
/* Send message to the room1. It broadcasts the data to all
the socket clients which are connected to the room1 */
io.sockets.in('room1').emit('function', {foo:bar});
ii) socket.broadcast.to().emit();
io.sockets.on('connection', function (socket) {
socket.on('function', function(data){
/* Broadcast to room1 except the sender. In other word,
It broadcast all the socket clients which are connected
to the room1 except the sender */
socket.broadcast.to('room1').emit('function', {foo:bar});
}
}
Socket.io
i) io.sockets.emit();
/* Send message to all. It broadcasts the data to all
the socket clients which are connected to the server; */
io.sockets.emit('function', {foo:bar});
ii) socket.broadcast.emit();
io.sockets.on('connection', function (socket) {
socket.on('function', function(data){
// Broadcast to all the socket clients except the sender
socket.broadcast.emit('function', {foo:bar});
}
}
Cheers