Hanu
Hanu

Reputation: 57

Reading Variable length messages in Qtcp readyRead()

The following code is intended to display an Image sent over network. I sent a header of 16 bytes which I use to calculate the size of image that follows and then read that many bytes and display the image. I used the concept at this link Tcp packets using QTcpSocket

void socket::readyRead()
{ 

while(socket->bytesAvailable() > 0) {
    quint8 Data[16];

    socket->read((char *)&Data,16);
    img_size = (((quint8)Data[1]<<8)+ (quint8)Data[0]) * (((quint8)Data[3]<<8)+ (quint8)Data[2]) * 1;
    QByteArray buffer = socket->read(img_size);


    while(buffer.size() < (img_size))
         {
            // qDebug() << buffer.size();
              socket->waitForReadyRead();
              buffer.append(socket->read((img_size)-(buffer.size()) ));
          }
    unsigned char* imgdatara = (unsigned char*)&buffer.data()[0];
      if( !image )
       image =  new QImage(imgdatara,32,640,QImage::Format_Grayscale8);
      else
      {
      delete image;
      image =  new QImage(imgdatara,32,640,QImage::Format_Grayscale8);
      }

      emit msg(image);
   }     
 }

My GUI says "not responding". How should I solve this?

Thanks

Upvotes: 0

Views: 216

Answers (1)

Vladimir Bershov
Vladimir Bershov

Reputation: 2832

This is 100% working code from the book of Max Schlee's "Qt 4.8 Professional programming". This is not a simple question, because on the readyRead() signal you can receive:
1. A complete block
2. Only a part of block
3. Several blocks together

void MyClass::onReceive()
{
    QDataStream in(m_pClient);
    in.setVersion(QDataStream::Qt_4_6); // Your version. Not necessary.

    for(;;)
    {
        if(m_nextBlockSize == 0)
        {
            if(m_pClient->bytesAvailable() < sizeof(m_nextBlockSize))
            {
                break;
            }
            else
            {
                in >> m_nextBlockSize; 
            }
        }

        if(m_pClient->bytesAvailable() < m_nextBlockSize)
        {
            break;
        }

        // Here you have each complete block
        processYourBlockHere(); // <=====

        m_nextBlockSize = 0;
    }
}

Update: useful links for you: Serializing Qt Data Types and QDataStream

Upvotes: 1

Related Questions