papercats/server.js

60 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-02-21 20:36:35 -05:00
var config = require("./config.json");
2019-02-21 11:19:33 -05:00
if (!(config.http_port >= 0 && config.http_port < 65536 && config.http_port % 1 === 0)) {
console.error("[ERROR] http_port argument must be an integer >= 0 and < 65536.");
process.exit();
}
if (!(config.ws_port >= 0 && config.ws_port < 65536 && config.ws_port % 1 === 0)) {
console.error("[ERROR] ws_port argument must be an integer >= 0 and < 65536.");
process.exit();
}
const finalhandler = require("finalhandler"),
http = require("http"),
serveStatic = require("serve-static");
2019-02-21 12:50:43 -05:00
//Serve up public/ folder
2019-01-15 10:42:15 -05:00
var serve = serveStatic("public/", {
2019-02-21 11:19:33 -05:00
"setHeaders": function(res, path) {
res.setHeader("Cache-Control", "public, max-age=0");
}
2019-01-15 10:42:15 -05:00
});
2017-02-28 02:20:32 -05:00
2019-02-21 12:50:43 -05:00
//Create server
2019-02-21 11:19:33 -05:00
try {
http.createServer(function onRequest(req, res) {
serve(req, res, finalhandler(req, res));
}).listen(config.http_port, config.hostname);
}
catch (e) {
console.error("[ERROR] hostname argument invalid.");
process.exit();
}
2019-01-16 03:57:36 -05:00
2019-02-21 11:19:33 -05:00
var server = http.createServer();
server.listen(config.ws_port);
2019-01-15 10:42:15 -05:00
var io = require("socket.io")(server);
io.set("transports", ["websocket"]);
2019-02-21 11:19:33 -05:00
const Game = require("./src/game-server.js");
var game = new Game();
2019-01-15 10:42:15 -05:00
io.on("connection", function(socket) {
socket.on("hello", function(data, fn) {
//TODO: error checking.
2019-02-22 00:22:21 -05:00
if (data.god && game.addGod(socket)) {
fn(true);
return;
}
2019-01-15 10:42:15 -05:00
if (data.name && data.name.length > 32) fn(false, "Your name is too long!");
2019-02-21 20:36:35 -05:00
else if (!game.addPlayer(socket, data.name)) fn(false, "There're too many platers!");
2019-01-15 10:42:15 -05:00
else fn(true);
});
socket.on("pings", function(fn) {
socket.emit("pongs");
socket.disconnect();
});
});
2019-02-21 11:19:33 -05:00
setInterval(function() {
game.tickFrame();
}, 1000 / 60);