title: Why can't my code read the number of bytes available on a QTcpSocket? Ideas?
body: <p>I have the following snippet of code in the body of a loop responsible for reading data from a QTcpSocket (nntp is a pointer to a QTcpSocket).</p>
  
  <pre><code>std::vector&lt;char&gt; buffer;
  int bytesAvailable = nntp-&gt;bytesAvailable();
  qDebug() &lt;&lt; "bytesAvailable: "&lt;&lt;bytesAvailable;
  if(bytesAvailable &lt;= 0) break;
  buffer.resize(bytesAvailable);
  bytesRead = nntp-&gt;read(&amp;buffer[0], bytesAvailable);
  qDebug() &lt;&lt; (nntp-&gt;state() == QAbstractSocket::ConnectedState);
  qDebug() &lt;&lt; "bytesRead: "&lt;&lt;bytesRead;
  </code></pre>
  
  <p>Intermittently, this outputs something akin to the following:</p>
  
  <pre><code>bytesAvailable:  24 
  true 
  bytesRead:  0 
  </code></pre>
  
  <p>And my code from there mis-behaves. This seems very strange to me and suggests that I completely misunderstand how QTcpSockets work. Surely if bytesAvailable > 0 then a subsequent read will mean that bytesAvailable bytes can be read into a buffer in which case bytesRead should == bytesAvailable. Or am I missing something? My current suspicion is that it could be a memory corruption of some sort..</p>
  
  <p>EDIT: Throwing in some nntp.errorString() messages reports that during this failure, the "Network operation timed out". I need to investigate what this means...(ideas?)</p>
  
  <p>EDIT 2: It seems that "Network operation timed out" just means that the read timed out. When the code works as it should (i.e. intermittently), I still get this 'error'.</p>
  
  <p>EDIT 3: The full algorithmic context for the above snippet of code can be found <a href="http://pastebin.com/dumLDp6J" rel="nofollow">at this pastebin link</a>.</p>
  
  <p>EDIT 4: A slightly different version of the function in EDIT 3 but still with the same problems nonetheless is at <a href="http://pastebin.com/biBzNKpw" rel="nofollow">this newer pastebin link</a></p>