Broadcast to all sockets

The broadcast server example from the getting started article is reproduced below

var app = require('express')();
var http = require('http').Server(app);
var io = require('')(http);

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html');

io.on('connection', function(socket) {
  console.log('a user connected');
  socket.broadcast.emit('user connected');
  io.emit('to all');

http.listen(3000, function() {
  console.log('listening on *:3000');

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 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 namespace ns1. If you were to emit using io.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

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



2 thoughts on “Broadcast to all sockets

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

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

Leave a Reply

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

You are commenting using your 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