node.js and socket.io - broadcast is undefined

Using Node.js and socket.io, the following works fine unti trying to broadcast back to the clients.

I am getting broadcast undefined?

var http = require('http'),
    sys  = require('sys'),
    fs   = require('fs'),
    io   = require('socket.io');

var server = http.createServer(function(request, response) {
  response.writeHead(200, {
    'Content-Type': 'text/html'
  });

  var rs = fs.createReadStream(__dirname + '/index.html');
  sys.pump(rs, response);

});

var socket = io.listen(server);
debugger;
socket.on('connection', function(client) {
  debugger;
  var username;

  client.send('Welcome to this socket.io chat server!');
  client.send('Please input your username: ');

  client.on('message', function(message) {
    if (!username) {
      username = message;
      client.emit('Welcome, ' + username + '!');
      return;
    }
    socket.broadcast.send('a message');
    //io.socket.send('a message');
    //io.socket.emit('message', username + ' sent: ' + message);
  });

});

server.listen(4000);

That's because broadcast is a method of an io.sockets.socket object (which would be client in your case), not of an io.sockets object (such as your misleadingly-named socket). You want client.broadcast....

It looks from your code like you're using a very old version of node (e.g. sys.pump()) and you may also be using an old version of socket.io.

If you want to send message from specific client to rest of the clients then use:

client.broadcast.send('a message');

To send message to all clients use:

socket.sockets.send('a message');

sys, pump, they are all deprecated.

https://github.com/joyent/node/wiki/API-changes-between-v0.6-and-v0.8 http://nodejs.org/api/util.html#util_util_pump_readablestream_writablestream_callback