8
io.sockets.on('connection', function(socket) {
    socket.object = socket.id;

    socket.on('updateObject', function(data) {
        // How to update socket.object here for all clients?
    });
});

How to do it?

Matt
  • 14,906
  • 27
  • 99
  • 149
owl
  • 4,201
  • 3
  • 22
  • 28
  • This might help http://stackoverflow.com/questions/6563885/socket-io-how-do-i-get-a-list-of-connected-sockets-clients – vinayr Jun 11 '14 at 04:55

2 Answers2

23

For the users using Socket.IO versions 1.0 or above this is the updated code for doing so.

Code to update socket object for all clients in a room

var clients = io.sockets.adapter.rooms['Room Name'].sockets;   

//to get the number of clients
var numClients = (typeof clients !== 'undefined') ? Object.keys(clients).length : 0;

for (var clientId in clients ) {

     //this is the socket of each client in the room.
     var clientSocket = io.sockets.connected[clientId];

     //you can do whatever you need with this
     clientSocket.emit('new event', "Updates");

}
Joseph238
  • 1,174
  • 1
  • 14
  • 22
Sony Mathew
  • 2,929
  • 2
  • 22
  • 29
  • 4
    The API has changed again. To access the array of clients for a particular room, use `clients = io.sockets.adapter.rooms['Room Name'].sockets`. – Joseph238 Mar 03 '16 at 20:01
  • to emit to a single room you can use : `io.to('roomName').emit('event, 'msg'); ` – Sebastien H. Apr 11 '17 at 10:14
  • 1
    Can anyone point the API's documentation at https://socket.io/docs/server-api/? I am unable to find. Thanks – igauravsehrawat May 31 '18 at 12:26
  • 1
    Somehow this also doesn't work for me. It always returns the error, `Cannot read property 'rooms' of undefined` any help? – Seba M Jul 16 '20 at 15:35
2

Please note that this function is not available anymore in socket.io versions higher then 1.0, it is recommended to keep a array of your socket.id's so you can iterate over them if need be. example by ynos1234

You can achieve this with the forEach function:

io.sockets.on('connection', function(socket) {
socket.object = socket.id;

    socket.on('updateObject', function(data) {
        io.sockets.clients('room').forEach(function (socket, data) {
            // goes through all clients in room 'room' and lets you update their socket objects
        });
    });
});
Community
  • 1
  • 1
GiveMeAllYourCats
  • 890
  • 18
  • 23