summaryrefslogtreecommitdiff
path: root/interactor/server.js
blob: 88e9f1060dec598e235af0f470a2a442f37e331e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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));