summaryrefslogtreecommitdiff
path: root/interactor/server.js
diff options
context:
space:
mode:
authorTom Smeding <tom.smeding@gmail.com>2018-07-01 21:12:11 +0200
committerTom Smeding <tom.smeding@gmail.com>2018-07-01 21:12:11 +0200
commit233160e17ff451e52621b10d5d00d99e7800c2db (patch)
treef700cf8f24896f72893ac4f9252d609d4a943449 /interactor/server.js
parentf283f00c084b3b563b923e33aabaffc4aa112e90 (diff)
Interactor
Diffstat (limited to 'interactor/server.js')
-rwxr-xr-xinteractor/server.js85
1 files changed, 85 insertions, 0 deletions
diff --git a/interactor/server.js b/interactor/server.js
new file mode 100755
index 0000000..88e9f10
--- /dev/null
+++ b/interactor/server.js
@@ -0,0 +1,85 @@
+#!/usr/bin/env node
+const http = require("http");
+const express = require("express");
+const socketio = require("socket.io");
+const child_process = require("child_process");
+
+const PORT = 8080;
+
+const app = express();
+const server = http.Server(app);
+const io = socketio(server);
+
+// gameid -> {pl: [socket]*{1,2}, started: Bool, nextServe: Int, score: [Int, Int]}
+const games = new Map();
+
+app.get("/", (req, res) => {
+ res.sendFile(__dirname + "/game.html");
+});
+
+const staticFiles = [
+ "/game.css",
+ "/game.js",
+ "/board.js",
+];
+
+app.get(staticFiles, (req, res) => {
+ res.sendFile(__dirname + req.path);
+});
+
+io.on("connection", (conn) => {
+ let proc = null;
+
+ conn.on("open", () => {
+ console.log("open");
+
+ proc = child_process.spawn("../main", {
+ stdio: ["pipe", "pipe", process.stderr]
+ });
+
+ conn.emit("open");
+
+ let lineBuffer = "";
+
+ proc.stdout.on("data", (data) => {
+ lineBuffer += data;
+ let idx;
+ while ((idx = lineBuffer.indexOf("\n")) != -1) {
+ conn.emit("line", lineBuffer.slice(0, idx));
+ lineBuffer = lineBuffer.slice(idx + 1);
+ }
+ });
+
+ proc.on("close", () => {
+ if (proc != null) {
+ console.log("close");
+ conn.emit("close");
+ proc.kill();
+ proc = null;
+ }
+ });
+
+ proc.on("error", (err) => {
+ if (proc != null) {
+ console.log("close");
+ conn.emit("close");
+ conn.emit("message", "The AI process encountered an error.");
+ proc = null;
+ }
+ });
+ });
+
+ conn.on("disconnect", () => {
+ if (proc != null) {
+ console.log("close");
+ proc.kill();
+ proc = null;
+ }
+ });
+
+ conn.on("line", (line) => {
+ proc.stdin.write(line + "\n");
+ });
+});
+
+server.listen(PORT, () => console.log("Listening on port " + PORT));