Antonio Laguna
Antonio Laguna

Reputation: 9282

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

I'm starting to learn socket.io 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('socket.io').listen(app)
  , fs = require('fs')

app.listen(8080);
var clients = [];

function handler (req, res) {
    fs.readFile(__dirname + '/index.html',
    function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading index.html');
        }
        res.writeHead(200);
        res.end(data);
    });
}
io.sockets.on('connection', function (socket) {
    clients[socket.id] = 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(socket.id) functions well BUT then, I won't be able to pop it a socket.id 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 :)

Upvotes: 1

Views: 3116

Answers (1)

alessioalex
alessioalex

Reputation: 63653

You should put the socket ids in the array like you did the first time, and on disconnect remove the socket.id 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) {
  clients.push(socket.id);
  socket.broadcast.emit('conection', { id: clients});
  socket.on('disconnect', function() {
    deleteFromArray(clients, socket.id);
  });
});

Resources:

Deleting array elements in JavaScript - delete vs splice

Upvotes: 7

Related Questions