-
Notifications
You must be signed in to change notification settings - Fork 557
/
server.js
executable file
·86 lines (79 loc) · 2.2 KB
/
server.js
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
86
#!/usr/bin/env node
const { Server: WebSocketServer } = require("ws");
const express = require("express");
const http = require("http");
const ParcelBundler = require("parcel-bundler");
const PORT = process.env.PORT || 8080;
const PUBLIC_DIR = "public";
const STATIC_DIR = "static";
/**
* Build and minify all client code for Express
*/
function bundleClient() {
const options = {
outDir: PUBLIC_DIR,
contentHash: true,
bundleNodeModules: true,
watch: false,
detailedReport: true
};
const bundler = new ParcelBundler("index.html", options);
return bundler.bundle();
}
/**
* Setup a quick Web Socket server
*/
function setupWSServer(server) {
const wss = new WebSocketServer({
server,
autoAcceptConnections: false
});
let actorCoordinates = { x: 100, y: 100 };
wss.on("connection", (ws) => {
ws.on("message", (rawMsg) => {
console.log(`RECV: ${rawMsg}`);
const incommingMessage = JSON.parse(rawMsg);
actorCoordinates.x = incommingMessage.x;
actorCoordinates.y = incommingMessage.y;
wss.clients.forEach((wsClient) => {
wsClient.send(JSON.stringify(actorCoordinates));
})
});
ws.send(JSON.stringify(actorCoordinates));
});
wss.on("listening", () => {
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
console.log(`WebSocketServer listening on ${bind}`);
});
return wss;
}
/**
* Setup an Express application and web server
*/
function setupServer() {
// Setup the Express application
const app = express();
app.set("port", PORT)
app.use("/", express.static(PUBLIC_DIR))
app.use("/static", express.static(STATIC_DIR))
// Setup the HTTP Web Server
const server = http.createServer(app);
server.listen(PORT);
server.on("listening", () => {
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
console.log(`WebServer listening on ${bind}`);
});
server.on("error", (err) => {
console.error(err);
process.exit(1);
});
return server;
}
if (require.main === module) {
bundleClient().then(() => {
const server = setupServer();
setupWSServer(server);
});
}