title: How to use QTcpSocket for high frequent sending of small data packages?
body: <p>We have two Qt applications. App1 accepts a connection from App2 through <code>QTcpServer</code> and stores it in an instance of <code>QTcpSocket* tcpSocket</code>. App1 runs a simulation with 30 Hz. For each simulation run, a <code>QByteArray</code> consisting of a few kilobytes is sent using the following code (from the main/GUI thread):</p>
  
  <pre><code>    QByteArray block;
      /* lines omitted which write data into block */
      tcpSocket-&gt;write(block, block.size());
      tcpSocket-&gt;waitForBytesWritten(1);
  </code></pre>
  
  <p>The receiver socket listens to the QTcpSocket::readDataBlock signal (in main/GUI thread) and prints the corresponding time stamp to the GUI.</p>
  
  <p>When both App1 and App2 run on the same system, the packages are perfectly in sync. However when App1 and App2 are run on different systems connected through a network, App2 is no longer in sync with the simulation in App2. The packages come in much slower. Even more surprising (and indicating our implementation is wrong) is the fact that when we stop the simulation loop, no more packages are received. This surprises us, because we expect from the TCP protocol that all packages will arrive eventually.</p>
  
  <p>We built the TCP logic based on Qt's <a href="http://qt-project.org/doc/qt-4.8/network-fortuneserver.html" rel="nofollow">fortune example</a>. The fortune server, however, is different, because it only sends one package per incoming client. Could someone identify what we have done wrong?</p>
  
  <p>Note: we use MSVC2012 (App1), MSVC2010 (App2) and Qt 5.2.</p>
  
  <p><strong>Edit:</strong> With a package I mean the result of a single simulation experiment, which is a bunch of numbers, written into <code>QByteArray block</code>. The first bits, however, contain the length of the QByteArray, so that the client can check whether all data has been received. This is the code which is called when the signal QTcpSocket::readDataBlock is emitted:</p>
  
  <pre><code>    QDataStream in(tcpSocket);
      in.setVersion(QDataStream::Qt_5_2);
  
      if (blockSize == 0) {
        if (tcpSocket-&gt;bytesAvailable() &lt; (int)sizeof(quint16))
           return; // cannot yet read size from data block
  
        in &gt;&gt; blockSize; // read data size for data block
      }
  
      // if the whole data block is not yet received, ignore it
      if (tcpSocket-&gt;bytesAvailable() &lt; blockSize)
        return;
  
      // if we get here, the whole object is available to parse
      QByteArray object;
      in &gt;&gt; object;
  
      blockSize = 0; // reset blockSize for handling the next package
  
      return;
  </code></pre>