Note that there are some explanatory texts on larger screens.

plurals
  1. POFaking a slow connect with TcpClient and Socket
    primarykey
    data
    text
    <p>I'm attempting to write an integration test to prove that a TCP client will correctly time out if an attempt to connect to the server is too slow. I have a <code>FakeServer</code> class that opens a <code>Socket</code> and listens for incoming connections:</p> <pre><code>public sealed class FakeServer : IDisposable { ... public TimeSpan ConnectDelay { get; set; } public void Start() { this.CreateSocket(); this.socket.Listen(int.MaxValue); this.socket.BeginAccept(this.OnSocketAccepted, null); } private void CreateSocket() { var ip = new IPAddress(new byte[] { 0, 0, 0, 0 }); var endPoint = new IPEndPoint(ip, Port); this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.socket.Bind(endPoint); } private void OnSocketAccepted(IAsyncResult asyncResult) { Thread.Sleep(this.connectDelay); this.clientSocket = this.socket.EndAccept(asyncResult); } } </code></pre> <p>Notice my attempt to delay the success of the connection via a call to <code>Thread.Sleep()</code>. Unfortunately, this does not work:</p> <pre><code>[Fact] public void tcp_client_test() { this.fakeServer.ConnectDelay = TimeSpan.FromSeconds(20); var tcpClient = new TcpClient(); tcpClient.Connect("localhost", FakeServer.Port); } </code></pre> <p>In the test above, the call to <code>tcpClient.Connect()</code> succeeds immediately, before the server-side <code>OnSocketAccepted</code> method is even called. I've had a look around the APIs and I can't see any obvious way for me to inject some server-side logic that must finish before the connection from the client is established.</p> <p>Is there any way for me to fake a slow server/connection using <code>TcpClient</code> and <code>Socket</code>?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload