-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-client.js
106 lines (86 loc) · 2.25 KB
/
test-client.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
console.log("node.js: %s", process.version);
var http = require('http');
var httpPort = 80;
var httpMethod = "GET";
var httpsAgent = new http.Agent({
keepAlive: true,
maxSockets: 1,
});
function getHttpsOptions(method, path) {
return {
agent: httpsAgent,
headers: {
'Content-Type': 'application/json',
},
method: method,
host: "localhost",
port: httpPort,
path: path,
};
}
function httpRequest(method, uri, data, callback) {
var errorFunction = function(error, data) {
if (callback) return callback(error, data)
throw error;
return false;
}
var successFunction = function(error, data) {
if (callback) return callback(error, data)
return true;
}
var handle = http.request(getHttpsOptions(method, uri), function(response) {
httpHandler(response, function (error, data) {
if (error) {
return errorFunction(error);
}
return successFunction(error, data);
});
});
handle.on('error', function(error){
return errorFunction(error);
});
if (data) {
handle.write(JSON.stringify(data));
}
handle.end();
}
function httpHandler(response, callback) {
var data = '';
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
if (response.statusCode !== 200) {
if (callback) return callback(new Error("unexpected HTTP response code"), data);
return false;
}
if (callback) return callback(null, data);
return true;
});
};
function doRequest(uri, callback) {
return httpRequest(httpMethod, uri, null, function (error, response) {
if (error) {
console.log("request failed");
} else {
console.log("request success");
}
if (callback) return callback(error, response);
return;
});
}
doRequest('/1', function () {
doRequest('/2');
});
doRequest('/3');
doRequest('/4', function () {
doRequest('/5');
});
doRequest('/6');
doRequest('/7', function () {
doRequest('/8');
});
doRequest('/9');
setTimeout(function() {
console.log('timeout');
}, 2500);