C# good practice waiting for TCP response
<p>While making a c# application for remote controlling cisco routers using TCP, I got the problem of waiting for a response from the router.</p>

<p>For the application I have to connect to a Cisco router using a TCP connection. After the connection has been made a networkstream will push my command to the Cisco router. To let the router process the command, I am using <code>Thread.Sleep</code>. This is not the best solution.</p>

<p>Here is the complete code to get a idea what my program is doing.</p>

<pre><code>        string IPAddress = "192.168.1.1";
        string message = "show running-config";  // command to run
        int bytes;
        string response = "";

        byte[] responseInBytes = new byte[4096];
        var client = new TcpClient();
        client.ConnectAsync(IPAddress, 23).Wait(TimeSpan.FromSeconds(2));
        if (client.Connected == true)
        {
            client.ReceiveTimeout = 3;
            client.SendTimeout = 3;
            byte[] messageInBytes = Encoding.ASCII.GetBytes(message);
            NetworkStream stream = client.GetStream();
            Console.WriteLine();
            stream.Write(messageInBytes, 0, messageInBytes.Count());    //send data to router
            Thread.Sleep(50);                                           // temporary way to let the router fill his tcp response
            bytes = stream.Read(responseInBytes, 0, responseInBytes.Length);
            response = Encoding.ASCII.GetString(responseInBytes, 0, bytes);
            return response;                                            //whole command output
        }
        return null;
</code></pre>

<p>What is a good and reliable way to get the full response.
Thanks for any help or command.</p>

<p><strong>More info</strong>: </p>

<p>The networksteam is always filled with something, most of the time it is filled with the cisco IOS login page. The biggest problem is to determine when the router is done filling up the response. 
The response I most of the time get:</p>

<blockquote>
  <p>"??\u0001??\u0003??\u0018??\u001f\r\n\r\nUser Access Verification\r\n\r\nUsername: "</p>
</blockquote>

<p>The return data will be diffent every time because it will be a result of a cisco command. This can vary from a short string to a very long string.</p>

<ul>
<li>mrmathijs95 -</li>
</ul>