-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.js
79 lines (61 loc) · 2.2 KB
/
middleware.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
const express = require('express');
const bodyParser = require('body-parser');
const { spawn } = require('child_process');
const app = express();
app.use(bodyParser.json());
let connectedClients = []; // Stores the current list of clients
// Endpoint to accept the name and launch the client
app.post('/start-client', (req, res) => {
const { name } = req.body;
if (!name) {
return res.status(400).send({ error: "Name is required." });
}
// Spawn the Client process
const clientProcess = spawn('./Client');
// Send the name to the C client
clientProcess.stdin.write(name + '\n');
clientProcess.stdout.on('data', (data) => {
console.log(`Client Output: ${data.toString()}`);
});
clientProcess.stderr.on('data', (data) => {
console.error(`Client Error: ${data.toString()}`);
});
clientProcess.on('close', (code) => {
console.log(`Client Process exited with code ${code}`);
});
res.send({ message: `Client started with name: ${name}` });
});
// Endpoint to fetch the list of connected clients
app.get('/clients', (req, res) => {
res.send({ clients: connectedClients });
});
// Start the server
app.listen(3001, () => {
console.log("Middleware server running on port 3001");
});
// Hook into the Server process to update client list
const serverProcess = spawn('./Server');
serverProcess.stdout.on('data', (data) => {
const output = data.toString().split('\n');
output.forEach(line => {
if (line.trim() === '') return;
const parts = line.split(' ');
if (parts.length === 3) {
const index = parseInt(parts[0].trim(), 10) - 1;
const name = parts[1].trim();
const status = parseInt(parts[2].trim(), 10);
if (status === 0) {
if (index >= 0 && index < connectedClients.length) {
connectedClients.splice(index, 1);
}
} else {
const client = { name, status };
connectedClients.push(client);
}
}
});
console.log('Updated Clients:', connectedClients);
});
serverProcess.stderr.on('data', (data) => {
console.error(`Server Error: ${data}`);
});