forked from pbininda/node8keepAliveTimeout
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
60 lines (49 loc) · 1.71 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
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const { isKeepAliveDisabled, readKeepAliveTimeout} = require("./utils");
const keepAliveTimeout = readKeepAliveTimeout();
const keepAliveDisabled = isKeepAliveDisabled();
let connections = 0;
const app = express();
app.use(bodyParser.json());
app.use((req, res, next) => {
console.log('Got request', req.method, req.path);
if (req.header('Origin')) {
res.header('Access-Control-Allow-Origin', req.header('Origin'));
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, ForcePreflight');
res.header('Access-Control-Allow-Credentials', 'true');
}
next();
});
let router = express.Router();
let prev;
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
router.post('/longpost', (req, resp) => {
++connections;
let now = new Date().getTime();
if (prev) {
let dt = now - prev;
console.log(`Format called ${dt}ms after previous. Open connections: ${connections}`);
}
prev = now;
setTimeout(() => {
resp.send(JSON.stringify({ status: 'OK' }));
--connections;
}, keepAliveTimeout * 3 - getRandomInt(20))
});
app.use('/', router);
let server = http.createServer(app);
if (!keepAliveDisabled) {
// workaround: set the keepAliveTimeout property
server.keepAliveTimeout = keepAliveTimeout;
console.log('Set keepAliveTimeout to', server.keepAliveTimeout);
}
else {
server.keepAliveTimeout = 0;
console.log('Disabling keepAliveTimeout');
}
server.listen(9666);