How to mantain current active sockets in + node.js?


I'm starting to learn and node.js I'm trying to do some pretty basic stuff (or so I think) but I'm unable to do.

Here is my node app:

var app = require('http').createServer(handler)
  , io = require('').listen(app)
  , fs = require('fs')

var clients = [];

function handler (req, res) {
    fs.readFile(__dirname + '/index.html',
    function (err, data) {
        if (err) {
            return res.end('Error loading index.html');
io.sockets.on('connection', function (socket) {
    clients[] = true;
    socket.broadcast.emit('conection', { id: clients});

I want to store connected clients and then, onConnection send them all clients connected. The point is, I don't know how to properly use the arrays on JavaScript because using clients.push( functions well BUT then, I won't be able to pop it a once a client disconnect without looping through the array, right?

Even if there is a method to obtain the current opened sockets, I want to do it in this way because I won't use the application with current socket sessions but with other thing.

I know it's a really noob question so, please, bear with me :)

Problem courtesy of: Antonio Laguna


You should put the socket ids in the array like you did the first time, and on disconnect remove the of the disconnected client. You don't need to loop thorough an array to delete an element, you can achieve that using array.indexOf(element) to determine the position of the element and array.splice(position, 1) to delete that element:

function deleteFromArray(my_array, element) {
  position = my_array.indexOf(element);
  my_array.splice(position, 1);

io.sockets.on('connection', function (socket) {
  socket.broadcast.emit('conection', { id: clients});
  socket.on('disconnect', function() {


Deleting array elements in JavaScript - delete vs splice

Solution courtesy of: alessioalex


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.