-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathserver.ts
59 lines (48 loc) · 1.73 KB
/
server.ts
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
import express = require("express");
var cors = require("cors");
var bodyParser = require("body-parser");
import EventEmitter from "./MyEmitter";
const { EventEmitterInstance: myEmitter } = EventEmitter;
const find = require("find-process");
import { Socket } from "socket.io";
import { runWorkerThread } from "./executor";
import { MyEmitterEvents, SocketEvents, WorkerTaskResponse } from "./Models";
const app: express.Application = express();
app.use(bodyParser.json());
app.use(cors());
var http = require("http").Server(app);
var io = require("socket.io")(http);
io.on("connection", (socket: Socket) => {
console.log("connected", socket.id);
socket.emit(SocketEvents.MESSAGE, `hello ${socket.id}`);
});
myEmitter.on(MyEmitterEvents.THREAD_RESPONSE, (threadResponse: WorkerTaskResponse) => {
console.log("an event occurred!", threadResponse.flag);
io.to(threadResponse.clientId).emit(SocketEvents.MESSAGE, threadResponse);
});
app.get("/health", function (req: express.Request, res: express.Response) {
res.send(`Hello World! ${new Date()}`);
});
app.post("/execute", function (req: express.Request, res: express.Response) {
const command = req.body.command as string;
const clientId = req.body.id;
runWorkerThread(command, clientId)
.then(function (result: any) {
res.status(200).send();
})
.catch(function (err) {
res.send(err);
});
});
app.post("/kill", function (req: express.Request, res: express.Response) {
console.log('kill', req.body);
const pid = req.body.pid as string;
const id = req.body.id;
process.kill(parseInt(pid));
myEmitter.emit("event", id, "Cancelled");
res.send("Killed");
});
const port = 4000;
http.listen(port, function () {
console.log("listening on localhost:" + port);
});