diff options
author | John Eisenmann <johneisenmann@Johns-iMac.local> | 2018-04-22 19:25:12 -0400 |
---|---|---|
committer | John Eisenmann <johneisenmann@Johns-iMac.local> | 2018-04-22 19:25:12 -0400 |
commit | f2a07747cd246e047b78cf783fd8f47c7fbd4b26 (patch) | |
tree | 8de806164572b4149c53fffb90e6944d090ec174 | |
parent | 2fcfe238f3a4c612fe5be36d6167ef44c5a5105c (diff) |
Using web sockets
-rw-r--r-- | breadQuest.js | 39 | ||||
-rw-r--r-- | package.json | 1 | ||||
-rw-r--r-- | public/javascript/game.js | 37 | ||||
-rw-r--r-- | routes/index.js | 25 | ||||
-rw-r--r-- | utils/page.js | 54 | ||||
-rw-r--r-- | views/game.html | 3 |
6 files changed, 104 insertions, 55 deletions
diff --git a/breadQuest.js b/breadQuest.js index 3302290..b17e08c 100644 --- a/breadQuest.js +++ b/breadQuest.js @@ -10,16 +10,9 @@ var session = require("express-session") var http = require("http"); var https = require("https"); var fs = require("fs"); +var expressWs = require("express-ws"); var app = express(); -module.exports = app; - -var index = require("./routes/index"); - -// view engine setup -app.set("views", path.join(__dirname, "views")); -app.set("view engine", "jade"); - var mode = app.get("env"); if (mode == "development") { console.log("WARNING: APPLICATION RUNNING IN DEVELOPMENT MODE!"); @@ -39,6 +32,25 @@ if (mode == "development") { process.exit(1); } +var server; +if (mode == "development") { + server = http.createServer(app); +} else { + var privateKey = fs.readFileSync("ssl.key", "utf8"); + var certificate = fs.readFileSync("ssl.crt", "utf8"); + var credentials = {key: privateKey, cert: certificate}; + server = https.createServer(credentials, app); +} +expressWs(app, server); + +module.exports = app; + +var index = require("./routes/index"); + +// view engine setup +app.set("views", path.join(__dirname, "views")); +app.set("view engine", "jade"); + app.engine("html", mustacheExpress()); var sessionSecret = fs.readFileSync("./sessionSecret.txt", "utf8") @@ -77,17 +89,6 @@ app.use(function(err, req, res, next) { res.render("error"); }); -var server; - -if (mode == "development") { - server = http.createServer(app); -} else { - var privateKey = fs.readFileSync("ssl.key", "utf8"); - var certificate = fs.readFileSync("ssl.crt", "utf8"); - var credentials = {key: privateKey, cert: certificate}; - server = https.createServer(credentials, app); -} - var portNumber = 2626; server.listen(portNumber, function() { diff --git a/package.json b/package.json index 0fe2821..66b7bc4 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "debug": "~2.6.3", "express": "~4.15.2", "express-session": "^1.15.2", + "express-ws": "^3.0.0", "jade": "~1.11.0", "morgan": "~1.8.1", "mustache-express": "^1.2.4", diff --git a/public/javascript/game.js b/public/javascript/game.js index d3404bf..2ffd6f3 100644 --- a/public/javascript/game.js +++ b/public/javascript/game.js @@ -74,7 +74,8 @@ var lKeyIsHeld = false; var guidelinePos = null; var guidelinePosInput; var guidelinePosInputIsFocused = false; - +var gameUpdateSocket; +var gameUpdateStartTimestamp; var moduleList = []; // Thanks to CatTail for this snippet of code. @@ -94,14 +95,16 @@ function betterModulus(number1, number2) { } } -function GameUpdateRequest() { +function performGameUpdateRequest() { isRequestingGameUpdate = true; - AjaxRequest.call(this, "gameUpdate", {}, {commandList: JSON.stringify(gameUpdateCommandList)}); + gameUpdateStartTimestamp = Date.now() / 1000; + gameUpdateSocket.send(JSON.stringify(gameUpdateCommandList)); gameUpdateCommandList = []; } -setParentClass(GameUpdateRequest, AjaxRequest); -GameUpdateRequest.prototype.respond = function(data) { +function handleGameUpdateRequest(data) { + var tempTimestamp = Date.now() / 1000; + document.getElementById("pingTime").innerHTML = Math.floor((tempTimestamp - gameUpdateStartTimestamp) * 1000); if (data.success) { var tempCommandList = data.commandList; var index = 0; @@ -168,9 +171,8 @@ GameUpdateRequest.prototype.respond = function(data) { hasStopped = true; window.location = "menu"; } - gameUpdateRequestDelay = 0.25 * framesPerSecond; + gameUpdateRequestDelay = 0.1 * framesPerSecond; isRequestingGameUpdate = false; - AjaxRequest.prototype.respond.call(this, data); } function addStartPlayingCommand() { @@ -1485,7 +1487,7 @@ function timerEvent() { addGetRespawnPosChangesCommand(); addGetStatsCommand(); addGetAvatarChangesCommand(); - new GameUpdateRequest(); + performGameUpdateRequest(); } } @@ -1629,6 +1631,21 @@ function initializeGame() { addStartPlayingCommand(); addGetGuidelinePosCommand(); - setInterval(timerEvent, Math.floor(1000 / framesPerSecond)); - setInterval(barTimerEvent, Math.floor(1000 / 30)); + var tempProtocol; + if (window.location.protocol == "http:") { + tempProtocol = "ws:"; + } else { + tempProtocol = "wss:"; + } + var tempAddress = tempProtocol + "//" + window.location.hostname + ":" + window.location.port + "/gameUpdate"; + gameUpdateSocket = new WebSocket(tempAddress); + gameUpdateSocket.onopen = function(event) { + setInterval(timerEvent, Math.floor(1000 / framesPerSecond)); + setInterval(barTimerEvent, Math.floor(1000 / 30)); + }; + gameUpdateSocket.onmessage = function(event) { + handleGameUpdateRequest(JSON.parse(event.data)); + }; } + + diff --git a/routes/index.js b/routes/index.js index fe524b5..4cbd41b 100644 --- a/routes/index.js +++ b/routes/index.js @@ -14,6 +14,7 @@ var checkAuthentication = pageUtils.checkAuthentication; var serveMessagePage = pageUtils.serveMessagePage; var JSON_ERROR_OUTPUT = pageUtils.errorOutput.JSON_ERROR_OUTPUT; var PAGE_ERROR_OUTPUT = pageUtils.errorOutput.PAGE_ERROR_OUTPUT; +var SOCKET_ERROR_OUTPUT = pageUtils.errorOutput.SOCKET_ERROR_OUTPUT; router.get("/index", function(req, res, next) { res.render("index.html", {message: "It works!"}); @@ -365,17 +366,23 @@ router.get("/game", checkAuthentication(PAGE_ERROR_OUTPUT), function(req, res, n res.render("game.html", {}); }); -router.post("/gameUpdate", checkAuthentication(JSON_ERROR_OUTPUT), function(req, res, next) { - function performUpdate() { - gameUtils.performUpdate(req.session.username, JSON.parse(req.body.commandList), function(result) { - res.json(result); +router.ws("/gameUpdate", checkAuthentication(SOCKET_ERROR_OUTPUT), function(ws, req, next) { + console.log("Opening socket."); + ws.on("message", function(message) { + var tempCommandList = JSON.parse(message); + if (gameUtils.isInDevelopmentMode) { + setTimeout(function() { + performUpdate(tempCommandList); + }, 50 + Math.floor(Math.random() * 150)); + } else { + performUpdate(tempCommandList); + } + }); + function performUpdate(commandList) { + gameUtils.performUpdate(req.session.username, commandList, function(result) { + ws.send(JSON.stringify(result)); }); } - if (gameUtils.isInDevelopmentMode) { - setTimeout(performUpdate, 50 + Math.floor(Math.random() * 150)); - } else { - performUpdate(); - } }); router.get("/leaderboard", function(req, res, next) { diff --git a/utils/page.js b/utils/page.js index 0e53d37..3178886 100644 --- a/utils/page.js +++ b/utils/page.js @@ -28,26 +28,45 @@ PageUtils.prototype.reportDatabaseError = function(error, errorOutput, req, res) } } -PageUtils.prototype.checkAuthentication = function(errorOutput) { - return function(req, res, next) { - if (mode == "development") { - if (!req.session.username) { - var tempUsername = req.query.username; - if (tempUsername) { - req.session.username = tempUsername; - } +function isAuthenticated(req) { + if (mode == "development") { + if (!req.session.username) { + var tempUsername = req.query.username; + if (tempUsername) { + req.session.username = tempUsername; } } - if (req.session.username) { - next(); - } else { - if (errorOutput == pageUtils.errorOutput.JSON_ERROR_OUTPUT) { - res.json({success: false, message: "You are not currently logged in."}); + } + return (typeof req.session.username !== "undefined"); +} + +PageUtils.prototype.checkAuthentication = function(errorOutput) { + if (errorOutput == pageUtils.errorOutput.SOCKET_ERROR_OUTPUT) { + return function(ws, req, next) { + if (isAuthenticated(req)) { + next(); + } else { + ws.on("message", function(message) { + ws.send(JSON.stringify({ + success: false, + message: "You are not currently logged in." + })); + }); } - if (errorOutput == pageUtils.errorOutput.PAGE_ERROR_OUTPUT) { - pageUtils.serveMessagePage(res, "You must be logged in to view that page.", "login", "Log In"); + }; + } else { + return function(req, res, next) { + if (isAuthenticated(req)) { + next(); + } else { + if (errorOutput == pageUtils.errorOutput.JSON_ERROR_OUTPUT) { + res.json({success: false, message: "You are not currently logged in."}); + } + if (errorOutput == pageUtils.errorOutput.PAGE_ERROR_OUTPUT) { + pageUtils.serveMessagePage(res, "You must be logged in to view that page.", "login", "Log In"); + } } - } + }; } } @@ -61,7 +80,8 @@ PageUtils.prototype.serveMessagePage = function(res, message, url, urlLabel) { PageUtils.prototype.errorOutput = { JSON_ERROR_OUTPUT: 0, - PAGE_ERROR_OUTPUT: 1 + PAGE_ERROR_OUTPUT: 1, + SOCKET_ERROR_OUTPUT: 2 } PageUtils.prototype.generateReturnUrl = function(req) { diff --git a/views/game.html b/views/game.html index bb8bacb..5148057 100644 --- a/views/game.html +++ b/views/game.html @@ -36,6 +36,9 @@ <li>L + WASD or Arrow Keys = Lock walk</li> </ul> <p> + Ping time: <span id="pingTime"></span> ms + </p> + <p> <a href="menu">Return to Menu</a> </p> </div> |