Skip to content

Instantly share code, notes, and snippets.

@olivier-spinelli
Created July 29, 2022 09:44
Show Gist options
  • Save olivier-spinelli/2acbdd68ad9aee9596dbe186dfaddd1f to your computer and use it in GitHub Desktop.
Save olivier-spinelli/2acbdd68ad9aee9596dbe186dfaddd1f to your computer and use it in GitHub Desktop.
A minimalist local echo server.
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