-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
99 lines (79 loc) · 2.63 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
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
/**
* Created by mac on 16/5/19.
*/
var net = require('net');
var CONFIG_FIELD = {
REMOTEIP:'remoteip',
REMOTEPORT:'remoteport',
LISTENPORT:'listenport'
};
exports.start = start;
/**
* start all proxy
* @param config
*/
function start(config){
if(!config){
throw new Error('no config set');
}
for(var k in config){
startProxy(k,config[k]);
}
}
function startProxy(name,config){
function info(message){
message = '\x1b[32m['+ new Date().toLocaleString() +']\x1b[m '+name+':info '+message;
console.log.apply(console,arguments);
}
function warn(message){
message = '\x1b[33m['+ new Date().toLocaleString() +']\x1b[m '+name+':warn '+message;
console.log.apply(console,arguments);
}
function debug(message){
message = '\x1b[36m['+ new Date().toLocaleString() +']\x1b[m '+name+':debug '+message;
console.log.apply(console,arguments);
}
function error(message){
message = '\x1b[31m['+ new Date().toLocaleString() +']\x1b[m '+name+':error '+message;
console.log.apply(console,arguments);
}
var server = net.createServer(/** @param {Socket}client**/function(client){
var remote;
info('client connected:',client.remoteAddress+':'+client.remotePort);
client.on('end',function(){
debug('client disconnected!',client.remoteAddress+':'+client.remotePort);
remote.destroy();
});
client.on('error',function(err){
error('client error:',client.remoteAddress+':'+client.remotePort,err);
remote.destroy();
});
var connectOption = {port:config[CONFIG_FIELD.REMOTEPORT],host:config[CONFIG_FIELD.REMOTEIP]};
//proxy client
remote = net.connect(connectOption,function(err){
if(err){
error('remote connected err!',err);
client.end(err);
}else{
info('remote connected ',connectOption);
client.pipe(remote);
remote.pipe(client);
}
});
remote.on('end',function(arg){
debug('remote disconnected!~:',client.remoteAddress);
client.destroy();
});
remote.on('error',function(err){
error('remote error!~:',client.remoteAddress,err);
client.destroy();
});
});
server.listen(config[CONFIG_FIELD.LISTENPORT],function(err){
if(err){
error('listen porterror:'+config[CONFIG_FIELD.LISTENPORT]);
}else{
info('listen port:'+config[CONFIG_FIELD.LISTENPORT]+' success!!');
}
});
}