Keep it simple.
Drain the network layer. I usually use an interface called INetworkChannel , which looks something like this:
public interface INetworkChannel : IDisposable { void Connect(IPEndPoint remoteEndPoint); void Send(byte[] buffer, int offset, int count); public event EventHandler Disconnected; public event EventHandler<ReceivedEventArgs> Received; }
This makes it easy to test everything, and you can create a SecureNetworkChannel class that uses SslStream or FastNetworkChannel that uses the new Async methods.
Details like which thread is used, or if you are using TcpClient or Socket , should not matter to the rest of the application.
Edit
Testing the implementation of INetworkingChannel also easy, as you now have a class with a very clear responsibility. I am creating a connection with my implementations to test them. Let TcpListener listen on port 0 for the OS to assign a free port.
I just make sure that it handles the sends and receives correctly and that it clears correctly when the connection is closed / broken.
source share