I'm writing a fairly straight forward Node server as a way of learning, and I've come across this problem.
When the server starts, I ping out via Socket.io an array of objects to each client machine. These objects simply have IP and PORT properties.
When testing on my machine, and only my machine, the log statement in the onLoad() function below prints the array once per second, perfect.
When I have multiple connections (3 tabs, laptop and friend's machine) all connected at the same time, the setInterval function duplicates for each connection, and emits to all machines connected multiple times.
Here's some code:
Client object
function Client(id, port) {
this.id = id;
this.port = port;
this.PrintClient = () => {
console.log("ID: " + this.id + ", Port: " + this.port);
};
};
Initial connection to the server from the client machine
app.get('/', (req, res) => {
console.log("request received!");
res.sendFile(path.join(__root, 'index.html'));
if(clients.length == 0) {
clients.push(new Client(req.connection.remoteAddress, req.connection.remotePort));
console.log("Clients was updated with the new client: " + JSON.stringify(clients[clients.length - 1]));
} else {
clients.forEach((client) => {
if(client.id !== req.connection.remoteAddress) {
var client = new Client(req.connection.remoteAddress, req.connection.remotePort);
clients.push(client);
console.log("Clients was updated with the new client: " + JSON.stringify(clients[clients.length - 1]));
}
});
};
});
(Checks if the IP exists in the array, if not adds it).
** and where I'm starting the setInterval poll**
(function init() {
// Launch the browser at the port we're using.
(function launch() {
child.exec('start chrome http://localhost:' + connPort);
})();
setInterval(() => {
io.emit('listReturn', JSON.stringify(clients));
}, 1000);
})();
In our front end, here's where the log statements are happening:
function onLoad() {
socket = io.connect();
console.log("onLoad() invoked")
socket.on('listReturn', (clientList) => {
var allClients = JSON.parse(clientList);
allClients.forEach((client) => {
console.log(JSON.stringify(client));
});
});
};
I was under the impression that the server was emitting the event listReturn every 1000ms, but it seems that every time a client machine connects it recreates that event and fires it.
Why is this happening?
via Jay Gould
No comments:
Post a Comment