I am trying to send an array of users that are connected to the server and send them to the client where I will loop through them.
app.js
io.on('connection', function (socket) {
socket.on('users', function (data) {
var clients = io.sockets.sockets;
socket.emit('clients', { user : clients });
});
});
index.html
socket.emit('users', { });
socket.on('clients', function(data) {
console.log(data);
//for(var obj in data) {
// console.log(data[obj]);
//}
});
The problem I am having is that it's throwing a RangeError on when trying to pass the users to the client.
There are two questions -
Am I doing this correctly? I am new to node.js and networking / server coding as a whole
Why would I get a RangeError.
Since, in the comments, you showed that it's a stack overflow error, it looks like the object pointed to by io.sockets.sockets
has a circular reference somewhere.
I'm making an assumption here based on what you said in your question, but since you are trying to simply send the list of connected users, maybe you can synthesize the clients
list prior to sending it out to the clients:
io.on('connection', function (socket) {
socket.on('users', function (data) {
var clients = io.sockets.sockets.map(function (client) {
// Derive some value---anything---from the `client` value. Once
// done that, return the resulting client value. Below, you can
// see that I have derived nothing, but I recommend that you *do*
// derive *something*.
return client;
});
socket.emit('clients', { user : clients });
});
});