-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
50 lines (40 loc) · 1.29 KB
/
index.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
var net = require('net');
var stream = require('stream');
var dns = require('dns');
var EventEmitter = require('events').EventEmitter;
var server = function(opts, callback) {
opts = opts || {};
var port = opts.port;
var forwardPort = opts.forwardPort;
var forwardHost = opts.forwardHost || 'localhost';
var s = net.createServer(function(client) {
var server = net.connect({port:forwardPort, host: forwardHost});
var serverStream = new stream.PassThrough();
var clientStream = new stream.PassThrough();
client.pipe(server).pipe(client);
client.pipe(clientStream);
server.pipe(serverStream);
var onclose = function() {
server.destroy();
client.destroy();
clientStream.end();
serverStream.end();
}
server.on('close', onclose);
server.on('error', onclose);
client.on('close', onclose);
client.on('error', onclose);
em.emit('connection', clientStream, serverStream);
});
if (port === forwardPort) {
dns.lookup(forwardHost, function(_, ip) {
if (ip === '127.0.0.1') return em.emit('error', new Error('The port and the forward port must be different.'));
s.listen(port, callback);
});
} else {
s.listen(port, callback);
}
var em = new EventEmitter();
return em;
};
module.exports = server;