title: How can I read from a socket repeatedly?
body: <p>To start I am coding in C#. I am writing data of varying sizes to a device through a socket. After writing the data I want to read from the socket because the device will write back an error code/completion message once it has finished processing all of the data. Currently I have something like this:</p>
  
  <pre><code>byte[] resultErrorCode = new byte[1];
  resultErrorCode[0] = 255;
  
  while (resultErrorCode[0] == 255)
  {
      try
      {
          ReadFromSocket(ref resultErrorCode);
      }
  
      catch (Exception)
      {
      }
  }
  Console.WriteLine(ErrorList[resultErrorCode[0] - 48]);
  </code></pre>
  
  <p>I use <code>ReadFromSocket</code> in other places, so I know that it is working correctly. What ends up happening is that the port I am connecting from (on my machine) changes to random ports. I think that this causes the firmware on the other side to have a bad connection. So when I write data on the other side, it tries to write data to the original port that I connected through, but after trying to read several times, the connection port changes on my side. </p>
  
  <p>How can I read from the socket continuously until I receive a completion command? If I know that something is wrong with the loop because for my smallest test file it takes 1 min and 13 seconds pretty consistently. I have tested the code by removing the loop and putting the code to sleep for 1 min and 15 seconds. When it resumes, it successfully reads the completion command that I am expecting. Does anyone have any advice?</p>