let running = true;
const server = http.createServer(handleRequest);
-function saveGames(exit) {
+function saveGames(callback) {
fs.writeFile("games.backup.json", JSON.stringify(games), function (err) {
if (err) {
console.error("ERROR: Cannot save games!");
- } else if (exit) {
- console.log("Games saved.");
}
- if (exit) {
- server.close();
+ if (typeof callback === "function") {
+ return callback(err);
}
});
}
function stop() {
- running = false;
- console.log("Closing connections and saving the game state...");
+ console.log("Saving games a first time");
+ if (saveTimeout) {
+ clearTimeout(saveTimeout);
+ saveTimeout = null;
+ }
- let listeningPlayerCount = 0;
- let gamesCount = 0;
+ saveGames(function () {
+ running = false;
+ console.log("Closing connections and saving the game state...");
- for (const gameID of Object.keys(games)) {
- const game = games[gameID];
- for (const listeningPlayer of game.listeningPlayers) {
- writeResponse(listeningPlayer, '{"stopping": 2000}', true);
- }
+ let listeningPlayerCount = 0;
+ let gamesCount = 0;
+
+ for (const gameID of Object.keys(games)) {
+ const game = games[gameID];
+ for (const listeningPlayer of game.listeningPlayers) {
+ writeResponse(listeningPlayer, '{"stopping": 2000}', true);
+ }
- if (game.listeningPlayers.length) {
- listeningPlayerCount += game.listeningPlayers.length;
- gamesCount++;
+ if (game.listeningPlayers.length) {
+ listeningPlayerCount += game.listeningPlayers.length;
+ gamesCount++;
+ }
}
- }
- console.log("Stopped", gamesCount, "games and", listeningPlayerCount, "player connections.");
- saveGames(true);
+ console.log("Stopped", gamesCount, "games and", listeningPlayerCount, "player connections.");
+ server.close(saveGames);
+ });
}
function stopKeepAlive(responseAndIsES) {