hi,

i've made a simple client/server example :

* The client connects to the server
* the server regulary sends data :
** size of buffer (short)
** buffer index (unsigned long)
** buffer, filled with zeros
* the client receives this data
** reads size
** reads buffer
** prints index.

Packet size should be always the same (19998).
But randomly, the client doesn't read the size, but reads 0. It seems there was a problem while reading the stream.

here's the log of my application :
...
onSocketReadyRead bytes= 7504
Bytes= 7504
Packet size= 19998
not enough data in stream
onSocketReadyRead bytes= 15008
Bytes= 15008
Packet size= 19998
not enough data in stream
onSocketReadyRead bytes= 20000
Bytes= 20000
Packet size= 19998
data read, packet index= 6733
onSocketReadyRead bytes= 0
onSocketReadyRead bytes= 3752
Bytes= 3752
Packet size= 0 <-- ERROR!

here's the code of the QThread client :
Qt Code:
  1. Client::Client(QObject *parent) : QThread(parent)
  2. {
  3.  
  4. }
  5.  
  6. Client::~Client()
  7. {
  8.  
  9. }
  10.  
  11. void Client::run()
  12. {
  13. pSocket = new QTcpSocket(this);
  14.  
  15. connect(pSocket, SIGNAL(readyRead()), this, SLOT(onSocketReadyRead()));
  16.  
  17. pSocket->connectToHost("192.168.50.77", 1234);
  18. if (!pSocket->waitForConnected())
  19. {
  20. qDebug()<<"Unable to connect";
  21. return;
  22. }
  23.  
  24. exec();
  25. }
  26.  
  27. void Client::onSocketReadyRead()
  28. {
  29. short sSize;
  30. char* data;
  31. unsigned long lPacketIndex;
  32. qint64 nBytes = pSocket->bytesAvailable();
  33.  
  34. qDebug()<<"onSocketReadyRead bytes="<<nBytes;
  35.  
  36. if (nBytes < 2)
  37. return;
  38. qDebug()<<"Bytes="<<nBytes;
  39. pSocket->peek((char*)&sSize, 2);
  40.  
  41. qDebug()<<"Packet size="<<sSize;
  42. if (sSize != 19998)
  43. {
  44. QMessageBox::critical(NULL, tr("error"), tr("This is it"));
  45. pSocket->disconnectFromHost();
  46. return;
  47. }
  48.  
  49. if (nBytes < 2 + sSize)
  50. {
  51. qDebug()<<" not enough data in stream";
  52. return;
  53. }
  54.  
  55. data = new char[sSize];
  56.  
  57. pSocket->read((char*)&sSize, 2);
  58. pSocket->read(data, sSize);
  59.  
  60. memcpy((char*)&lPacketIndex, data, 4);
  61.  
  62. qDebug()<<" data read, packet index="<<lPacketIndex;
  63.  
  64. delete data;
  65. }
To copy to clipboard, switch view to plain text mode 

What do i do that i should not do?
Is it a Qt bug?
This problem is random but can be reproduced more easily with a corrupted network (bad wifi connection, etc...)
it MAY be caused by TCP packet retransmission on timeout (i've seen such retransmission with wireshark)

thanks