@@ -5,21 +5,27 @@ namespace Socksy.Core.Network;
55internal sealed class TcpServer : IDisposable
66{
77 private readonly TcpListener _listener ;
8- private readonly Func < TcpClient , Task > _onConnectionEstablished ;
8+ private readonly Func < int , Request , Task > _onConnectionEstablished ;
99 private CancellationTokenSource ? _cancellationTokenSource ;
1010 private CancellationToken _cancellationToken ;
11+ private IPEndPoint _localEndPoint ;
1112 private int _activeRequests ;
1213 private bool _isListening ;
14+ private int _reqNum = 0 ;
1315
14- public TcpServer ( IPEndPoint localEndPoint , Func < TcpClient , Task > onConnectionEstablished )
16+ public TcpServer ( IPEndPoint localEndPoint , Func < int , Request , Task > onConnectionEstablished )
1517 {
18+ _localEndPoint = localEndPoint ;
1619 _listener = new TcpListener ( localEndPoint ) ;
1720 _onConnectionEstablished = onConnectionEstablished ;
1821 _isListening = false ;
1922 }
2023
2124 public bool IsListening => _isListening ;
2225
26+ public int ListeningPort => _localEndPoint . Port ;
27+ public IPAddress ListeningAddress => _localEndPoint . Address ;
28+
2329 public void Start ( )
2430 {
2531 if ( _isListening )
@@ -34,7 +40,7 @@ public void Start()
3440
3541 public void Stop ( )
3642 {
37- if ( ! _isListening )
43+ if ( ! _isListening )
3844 return ;
3945
4046 _listener . Stop ( ) ;
@@ -45,20 +51,22 @@ public void Stop()
4551
4652 private async Task MainLoop ( )
4753 {
48- while ( ! _cancellationToken . IsCancellationRequested )
54+ while ( ! _cancellationToken . IsCancellationRequested )
4955 {
5056 var tcpClient = await _listener . AcceptTcpClientAsync ( _cancellationToken ) ;
5157 Interlocked . Add ( ref _activeRequests , 1 ) ;
58+ Interlocked . Add ( ref _reqNum , 1 ) ;
5259
53- _ = _onConnectionEstablished ( tcpClient ) . ContinueWith ( ( t ) => {
60+ _ = _onConnectionEstablished ( _reqNum , Request . CreateFromTcpClient ( tcpClient ) ) . ContinueWith ( ( t ) =>
61+ {
5462 Interlocked . Add ( ref _activeRequests , - 1 ) ;
5563 } ) ;
5664 }
5765 }
5866
5967 private async Task WaitForAllActiveConnectionRequestsToComplete ( )
6068 {
61- while ( _activeRequests > 0 )
69+ while ( _activeRequests > 0 )
6270 {
6371 await Task . Delay ( 10 ) ;
6472 }
0 commit comments