Broadcast to all sockets


The broadcast server example from the socket.io how-to is reproduced below:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.broadcast.emit('user connected');
});

io.sockets.emit('to all');

The user connected event will be broadcast to all sockets except the one that just connected. The to all event is broadcast to all the sockets.

You can also broadcast some event to all the sockets in a namespace. For example:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  socket.broadcast.emit('user connected');
});

var ns1 = io.of('/ns1');
ns1.on('connection', function (socket) {
  socket.broadcast.emit('user connected');
});

ns1.emit('to all');

The to all event is emitted to all the sockets in ns1. If you were to emit using io.sockets.emit instead, the event would not be received by any of the sockets in ns1.

The client script that receives messages for namespace ns1 may look like this:

<script>
  var ns1 = io.connect('http://localhost/ns1');
  
  ns1.on('to all', function () {
    console.log('to all');
  });
</script>

2 thoughts on “Broadcast to all sockets

    1. Been a while this was asked. For posterity’s sake

      <script>
        var ws = io.connect('http://localhost');
         
        ws.on('user connected', function () {
          console.log('user connected');
        });
      </script>
      

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s