Created
July 29, 2022 09:44
-
-
Save olivier-spinelli/2acbdd68ad9aee9596dbe186dfaddd1f to your computer and use it in GitHub Desktop.
A minimalist local echo server.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EchoTcpServer | |
{ | |
readonly int _port; | |
public EchoTcpServer( int port ) | |
{ | |
_port = port; | |
} | |
public async Task<Exception?> Run( CancellationToken cancel ) | |
{ | |
TcpListener listener = new TcpListener( IPAddress.Loopback, _port ); | |
listener.Start(); | |
try | |
{ | |
try | |
{ | |
using( TcpClient client = await listener.AcceptTcpClientAsync() ) | |
{ | |
NetworkStream stream = client.GetStream(); | |
// Yes... this works like a charm! :) | |
await stream.CopyToAsync( stream, cancel ); | |
} | |
} | |
finally | |
{ | |
listener.Stop(); | |
} | |
} | |
catch( OperationCanceledException ) | |
{ | |
} | |
catch( Exception ex ) | |
{ | |
return ex; | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment