From 14b9cd1176aa72c58abf832775c6b5d585470f0f Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sun, 9 May 2021 00:53:54 +0800 Subject: [PATCH] feat: update --- bin/main.dart | 57 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/bin/main.dart b/bin/main.dart index b90bb5e..ef18cb4 100644 --- a/bin/main.dart +++ b/bin/main.dart @@ -2,6 +2,12 @@ import 'dart:convert'; import 'dart:io'; import 'config.dart'; +int createdConnectionCount = 0; +int runningConnectionCount = 0; +int upstreamBytes = 0; +int downstreamBytes = 0; +Map createdConnectionMap = {}; + void main(List arguments) { final listenAddress = "127.0.0.1"; final listenPort = 8801; @@ -34,9 +40,54 @@ void main(List arguments) { void startListen(HostAndPort listen, HostAndPort target) { ServerSocket.bind(listen.host, listen.port).then((serverSocket) { - Socket.connect(target.host, target.port).then((clientSocket) { - // TODO ... + 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, + ); + }); }); - // serverSocket.listen((event) { }) }); }