55 using System . Net ;
66 using System . Net . Sockets ;
77 using System . Text ;
8+ using System . Threading ;
89 using System . Threading . Tasks ;
910
1011 using SyslogProxy . Messages ;
@@ -13,11 +14,14 @@ public class Proxy
1314 {
1415 private readonly Action < string > messageHandler ;
1516
17+ private readonly CancellationToken cancellationToken ;
18+
1619 private const int BufferSize = 2048 ;
1720
18- public Proxy ( Action < string > messageHandler )
21+ public Proxy ( Action < string > messageHandler , CancellationToken cancellationToken )
1922 {
2023 this . messageHandler = messageHandler ;
24+ this . cancellationToken = cancellationToken ;
2125 var tcp = new TcpListener ( IPAddress . Any , Configuration . ProxyPort ) ;
2226
2327 tcp . Start ( ) ;
@@ -26,7 +30,7 @@ public Proxy(Action<string> messageHandler)
2630
2731 private async Task AcceptConnection ( TcpListener listener )
2832 {
29- while ( true )
33+ while ( ! this . cancellationToken . IsCancellationRequested )
3034 {
3135 var client = await listener . AcceptTcpClientAsync ( ) . ConfigureAwait ( false ) ;
3236 this . EchoAsync ( client ) . ConfigureAwait ( false ) ;
@@ -35,7 +39,8 @@ private async Task AcceptConnection(TcpListener listener)
3539
3640 private async Task EchoAsync ( TcpClient client )
3741 {
38- Console . WriteLine ( "New client connected." ) ;
42+ var ipAddress = ( ( IPEndPoint ) client . Client . RemoteEndPoint ) . Address . ToString ( ) ;
43+ Logger . Information ( "New client connected from IP: [{0}]." , ipAddress ) ;
3944 using ( client )
4045 {
4146 var stream = client . GetStream ( ) ;
@@ -45,17 +50,16 @@ private async Task EchoAsync(TcpClient client)
4550 {
4651 var timeoutTask = Task . Delay ( TimeSpan . FromSeconds ( Configuration . TcpConnectionTimeout ) ) ;
4752 Array . Clear ( buf , 0 , BufferSize ) ;
48- var amountReadTask = stream . ReadAsync ( buf , 0 , buf . Length ) ;
53+ var amountReadTask = stream . ReadAsync ( buf , 0 , buf . Length , this . cancellationToken ) ;
4954 var completedTask = await Task . WhenAny ( timeoutTask , amountReadTask )
5055 . ConfigureAwait ( false ) ;
5156 if ( completedTask == timeoutTask )
5257 {
53- Console . WriteLine ( "Client timed out" ) ;
58+ Logger . Information ( "Client with IP [{0}] timed out." , ipAddress ) ;
5459 break ;
5560 }
5661
57- var amountRead = amountReadTask . Result ;
58- if ( amountRead == 0 )
62+ if ( amountReadTask . Result == 0 )
5963 {
6064 break ;
6165 }
@@ -69,7 +73,7 @@ private async Task EchoAsync(TcpClient client)
6973 }
7074 }
7175 }
72- Console . WriteLine ( "Client disconnected" ) ;
76+ Logger . Information ( "Client with IP [{0}] disconnected." , ipAddress ) ;
7377 }
7478 }
7579}
0 commit comments