title: How to send files over tcp with TcpListener/Client? SocketException problem
body: <p>I'm developing a simple application to send files over TCP using the TCPListener and TCPClient classes. Here's the code that sends the file.</p>
  
  <p>Stop is a volatile boolean which helps stopping the process at any time and WRITE_BUFFER_SIZE might be changed in runtime (another volatile)</p>
  
  <pre><code>while (remaining &gt; 0 &amp;&amp; !stop)
  {
    DateTime current = DateTime.Now;
    int bufferSize = WRITTE_BUFFER_SIZE;
    buffer = new byte[bufferSize];
    int readed = fileStream.Read(buffer, 0, bufferSize);
    stream.Write(buffer, 0, readed);
    stream.Flush();
    remaining -= readed;
    // Wait in order to guarantee send speed
    TimeSpan difference = DateTime.Now.Subtract(current);
    double seconds = (bufferSize / Speed);
    int wait = (int)Math.Floor(seconds * 1000);
    wait -= difference.Milliseconds;
    if (wait &gt; 10)
      Thread.Sleep(wait);
  }                
  stream.Close();
  </code></pre>
  
  <p>and this is the code that handles the receiver side:</p>
  
  <pre><code>do
  {
    readed = stream.Read(buffer, 0, READ_BUFFER_SIZE);
    // write to .part file and flush to disk
    outputStream.Write(buffer, 0, readed);
    outputStream.Flush();
    offset += readed;
  } while (!stop &amp;&amp; readed &gt; 0);
  </code></pre>
  
  <p>Now, when the speed is low (about 5KBps) everything works ok but, as I increase the speed the receiver size becomes more prone to raise a SocketException when reading from the stream. I'm guessing it has to do with the remote socket being closed before all data can be read, but What's the correct way to do this? When should I close the sending client?</p>
  
  <p>I haven't found any good examples of file transmission on google, and the ones that I've found have a similar implementation of what I'm doing so I guess I'm missing something.</p>
  
  <p><strong>Edit:</strong> I get this error "Unable to read data from the transport connection". This is an IOException whose inner exception is a SocketException.</p>
  
  <p>I've added this in the sender function, still I get the same error, the code never reaches the stream.close() and of course the tcpclient never really get closed... so I'm completely lost now.</p>
  
  <pre><code>buffer = new byte[1];
  client.Client.Receive(buffer);
  stream.Close();
  </code></pre>