Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Node.js was something I was really interested forawhile and I used it in one of my project to make a multiplayer game.</p> <p><code>io.sockets.in().emit()</code> and <code>socket.broadcast.to().emit()</code> are the main two emit methods we use in Socket.io's Rooms (<a href="https://github.com/LearnBoost/socket.io/wiki/Rooms">https://github.com/LearnBoost/socket.io/wiki/Rooms</a>) 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.</p> <p>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 <code>io.sockets.emit()</code> and <code>socket.broadcast.emit()</code>. </p> <p>Anyway I'll try to give the example codes with the comments to explain. See if it helps;</p> <p><strong>Socket.io Rooms</strong></p> <p>i) io.sockets.in().emit();</p> <pre><code>/* 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}); </code></pre> <p>ii) socket.broadcast.to().emit();</p> <pre><code>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}); } } </code></pre> <p><strong>Socket.io</strong></p> <p>i) io.sockets.emit();</p> <pre><code>/* 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}); </code></pre> <p>ii) socket.broadcast.emit();</p> <pre><code>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}); } } </code></pre> <p>Cheers</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload