-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
66 lines (51 loc) · 2.06 KB
/
app.js
File metadata and controls
66 lines (51 loc) · 2.06 KB
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
const express = require('express');
const WebSocket = require('ws');
const path = require('path');
const http = require('http');
/* Store the message from client */
var messageServer = [];
var factorialResult = 0;
/* Server port */
const PORT = process.env.PORT || 3746;
/* Tell express to deliver files found in this folder*/
const PUBLIC = path.join(__dirname, 'public');
const app = express()
.use(express.static(PUBLIC));
/* Initialize an http server */
const server = http.createServer(app);
/* Initialize the WebSocket server instance */
const wss = new WebSocket.Server({ server });
/* Server port */
server.listen(PORT, function listening() {
console.log('Listening on %d', server.address().port);
});
/* On any connection */
wss.on('connection', (ws) => {
/* Connection is OK then add an event */
ws.on('message', (message) => {
/* Clean variables */
messageServer = [];
factorialResult = 0;
/* Log the received message */
console.log(`Message received from client: ${message}`);
/* Parse the message */
messageServer = JSON.parse(message);
/* Generate a python process using nodejs child_process module */
const spawn = require('child_process').spawn;
const py_process = spawn('python3', ["python/factorial.py"]);
/* Send the number to py_process */
py_process.stdin.write(messageServer.number.toString());
/* Close the stream */
py_process.stdin.end();
/* Define what to do on everytime node application receives data from py_process */
py_process.stdout.on('data', function(data){
factorialResult = data.toString();
});
/* At the end, send the result from py_process computing to client */
py_process.stdout.on('end', function(){
/* Send the message back to the client */
ws.send(JSON.stringify({ time: messageServer.time, number: messageServer.number, fact: factorialResult }));
});
});
console.log(`Have a connection at port ${server.address().port}`);
});