-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
70 lines (61 loc) · 1.58 KB
/
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
const { io } = require('socket.io-client');
const socket = io('ws://manager-node.begging.tech:8888');
socket.on('connect', () => {
console.log('Connected with server');
});
socket.on('http-request', async (msg) => {
try {
let httpReq = JSON.parse(msg);
var bdy = await sendReq(
httpReq.host,
httpReq.port,
httpReq.path,
httpReq.method,
httpReq.secure,
httpReq.headers,
httpReq.body);
socket.emit('http-response', JSON.stringify({status: 200, headers: {}, body: bdy}));
}
catch (e) {
socket.emit('http-response', JSON.stringify({status: 400, headers: {}, body: {error: 'Unknown'}}));
}
});
const http = require('http');
const https = require('https');
function sendReq(host, port, path, method, secure, headers, body) {
return new Promise(async function(succeed, fail) {
const options = {
hostname: host,
port: port,
path: path,
method: method,
headers: headers
};
const request = http.request(options, response => {
var data = '';
response.on('data', chunk => {
data += chunk;
});
response.on('end', () => {
var body = null;
try {
body = JSON.parse(data);
} catch (err) {}
if (body == null) {
fail(data);
return;
}
if (~~(response.statusCode / 100) == 2) {
succeed(body);
} else {
fail(body);
}
});
});
request.on('error', err => {
fail(err);
});
if (body) request.write(JSON.stringify(body));
request.end();
});
}