Files
simple-dart-tcp-proxy/bin/main.dart
2021-05-22 00:50:41 +08:00

74 lines
2.3 KiB
Dart

import 'dart:io';
import 'config.dart';
int createdConnectionCount = 0;
int runningConnectionCount = 0;
int upstreamBytes = 0;
int downstreamBytes = 0;
Map<int, bool> createdConnectionMap = <int, bool>{};
Future<void> main(List<String> arguments) async {
print('Arguments: ' + arguments.toString());
final proxyConfig = await loadProxyConfig(arguments[0]);
for (final tcpListen in proxyConfig.tcpListens) {
final listen = parseHostAndPort(tcpListen.listen);
final target = parseHostAndPort(tcpListen.backend);
startListen(listen, target);
}
}
void startListen(HostAndPort listen, HostAndPort target) {
ServerSocket.bind(listen.host, listen.port).then((serverSocket) {
serverSocket.listen((Socket socket) {
Socket.connect(target.host, target.port).then((clientSocket) {
final createdConnectionIndex = createdConnectionCount;
createdConnectionCount++;
runningConnectionCount++;
createdConnectionMap[createdConnectionIndex] = true;
socket.listen(
(event) {
upstreamBytes += event.lengthInBytes;
clientSocket.write(event);
},
onError: (error, StackTrace stackTrace) {
if (createdConnectionMap.remove(createdConnectionIndex) != null) {
runningConnectionCount--;
}
print(
'Error in connection: ' + error + " " + stackTrace.toString());
},
onDone: () {
if (createdConnectionMap.remove(createdConnectionIndex) != null) {
runningConnectionCount--;
}
clientSocket.destroy();
},
cancelOnError: true,
);
clientSocket.listen(
(event) {
downstreamBytes += event.lengthInBytes;
socket.write(event);
},
onError: (error, StackTrace stackTrace) {
if (createdConnectionMap.remove(createdConnectionIndex) != null) {
runningConnectionCount--;
}
print(
'Error in connection: ' + error + " " + stackTrace.toString());
},
onDone: () {
if (createdConnectionMap.remove(createdConnectionIndex) != null) {
runningConnectionCount--;
}
socket.destroy();
},
cancelOnError: true,
);
});
});
});
}