Cannot read complete data, bytes available != actual bytes read



  • Hello All,

    I am a newbie to QT. I am developing an application that is using QTCPSocket.
    I have created a signal for reading as below:
    @
    connect(m_pSocket,SIGNAL(readyRead()),SLOT(SocketDataReceived()));
    @

    and code to read data is:
    @
    void ABC::SocketDataReceived()
    {
    int nBytesAvaialble=m_pSocket->bytesAvailable();
    LOGDEBUG(CM,"SocketDataReceived : bytes Available initialially = " << nBytesAvaialble);

    QString m_qstrNextMesssage;
    
    while (nBytesAvaialble > 0)
    {
        m_qstrNextMesssage.append(m_pSocket->read(nBytesAvaialble));
        nBytesAvaialble = m_pSocket->bytesAvailable();
    }
    
    if(m_qstrNextMesssage.length() <= 0 )
    {
        LOGWARN(CM, "No data is read in this read API");
        return;
    }
    LOGDEBUG(CM, "Bytes read = " << m_qstrNextMesssage.length());
    LOGDEBUG(CM, m_qstrNextMesssage.toLatin1().data());
    emit DataReceived(m_qstrNextMesssage);
    m_qstrNextMesssage.clear();
    

    }
    @

    But when I run this code, the log I am getting shows that available bytes are not equal to bytes read (I tried using read() and then readAll() APIs).
    @
    [01/16/2015 14:53:05:801] [15976] [DEBUG] [CM] SocketDataReceived : bytes Available initialially = 412
    [01/16/2015 14:53:05:801] [15976] [DEBUG] [CM] Bytes read = 145

    Received data of length 145

    [01/16/2015 14:53:06:274] [15976] [DEBUG] [CommunicationManager] SocketDataReceived : bytes Available initialially = 146
    [01/16/2015 14:53:06:294] [15976] [DEBUG] [CommunicationManager] Bytes read = 145

    Received data of length 145
    @

    So, in 1st read call bytes available = 412, actual bytes read = 145
    in 2nd read call bytes available = 146, actual bytes read = 145

    So, where are 412-145 = 267 ? they should be available in next read call right ? So in next read should show bytes available as atleast 267.

    What is causing the loss of data here ? Please help.

    -Thanks,
    Kavita

    [Edited - Please use code tags "@@" - p3c0]



  • First of all, when placing code please use the @ before and @ after the snippets. Then the forum will display them as if real code.
    The we might be able to support you.


  • Moderators

    i don't know which data you are receiving on the socket, but count the read bytes directly and not from the string. Try this:
    @
    qint64 nBytesAvaialble=m_pSocket->bytesAvailable(); //<-- not using qint64 may cause possible loss of int-data here
    ...
    QByteArray readData = m_pSocket->read(nBytesAvaialble); // or use readAll()
    qint64 readBytes = readData.size();
    m_qstrNextMesssage.append(readData);
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.