-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy-server.js
78 lines (65 loc) · 2.19 KB
/
proxy-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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const fs = require('fs');
const http = require('http');
const WebSocket = require('ws');
var httpProxy = require('http-proxy');
const html = fs.readFileSync('index.html');
const clientScript = fs.readFileSync('proxy-client.js');
let portForThisUi = 3001; // should get from command line arg?
const server = http.createServer((req, res) => {
if (req.url === '/favicon.ico') return res.end('');
if (req.url === '/script') {
res.setHeader("Content-Type", "text/javascript");
return res.end(clientScript);
}
res.end(html);
}).listen(portForThisUi);
console.info(`Open browser to localhost:${portForThisUi}`);
const wssForThisUi = new WebSocket.Server({ server });
let thisUiWebSocket, theOtherClientWebsocket, theOtherServerWebsocket;
let stopped = true;
wssForThisUi.on('connection', function connection(ws) {
thisUiWebSocket = ws;
thisUiWebSocket.on('message', function incoming(message) {
const toInject = JSON.parse(message);
if (toInject.length) {
stopped = false;
inject(toInject);
} else {
stopped = true;
}
});
});
const theOtherServerPort = 3000;
const target = 'http://localhost:' + theOtherServerPort; // should get from input?
const portForTheOtherClient = 3002; // should get from input?
const proxy = httpProxy.createProxyServer({});
const httpForTheOtherClient = http.createServer((req, res) => {
proxy.web(req, res, {target});
}).listen(portForTheOtherClient);
console.info(`Open browser to localhost:${portForTheOtherClient}`);
const wssForTheOtherClient = new WebSocket.Server({server: httpForTheOtherClient});
wssForTheOtherClient.on('connection', function connection(ws) {
theOtherClientWebsocket = ws;
theOtherServerWebsocket = new WebSocket(target);
theOtherServerWebsocket.on('message', (message) => {
thisUiWebSocket.send(message);
theOtherClientWebsocket.send(message);
});
theOtherClientWebsocket.on('message', (message) => {
theOtherServerWebsocket.send(message);
});
});
function inject(toInject) {
toInject.forEach(({time, msg}) => {
setTimeout(() => {
if (!stopped && theOtherClientWebsocket) {
theOtherClientWebsocket.send(msg);
}
}, time);
});
setTimeout(() => {
if (!stopped) {
inject(toInject);
}
}, toInject.slice(-1)[0].time);
}