-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (69 loc) · 1.86 KB
/
index.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
const dgram = require('dgram');
const express = require('express');
const expressWs = require('express-ws');
const path = require('path');
const config = require('./config.json');
const NodeMgr = require('./class/NodeMgr');
const nodeMgr = new NodeMgr();
const WebClientMgr = require('./class/WebClientMgr');
const webClientMgr = new WebClientMgr();
nodeMgr.on('update', msg => {
webClientMgr.broadcast(nodeMgr);
});
webClientMgr.on('command', (...args) => {
nodeMgr.execute(...args)
});
webClientMgr.on('server_command', (cmd, cb) => {
console.log(`Executing: ${cmd}`);
switch (cmd) {
case 'stop':
cb(undefined, {
'type': 'server_execute',
'content': {
'text': 'Stopping Server',
'node': 'Server'
}
});
process.exit();
break;
case 'clear':
case 'prune':
cb(undefined, {
'type': 'server_execute',
'content': {
'text': `${cmd} ${nodeMgr[cmd]()} Nodes`,
'node': 'Server'
}
});
break;
default:
cb(new Error('unknown command: ' + cmd));
}
});
const app = express();
expressWs(app);
app.use(express.static(path.join(__dirname, 'static')));
app.ws('/ws', (ws, req) => {
webClientMgr.addClient(ws);
});
const expressServer = app.listen(config.express.port, () => {
const address = expressServer.address();
console.log(`Express listening on port ${address.port}`);
});
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
try {
nodeMgr.handleData(JSON.parse(msg), rinfo);
} catch (e) {
console.error('Invalid Client Message!', e);
}
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening on port ${address.port}`);
});
server.bind(config.udp.port);