TcpSocket读取错误的数据

TcpSocket reads wrong data

本文关键字:数据 取错误 读取 TcpSocket      更新时间:2023-10-16

我想通过QTcpSocket操作传输数据。为了告诉接收者他将接收多少数据,我首先发送数据量,然后发送数据本身。发送数据时,它看起来像

    QByteArray data = fortunes[counter%7].toUtf8();
    this->counter++;
    if(Server::clientConnection != NULL)
    {
        std::string s= std::to_string(data.size());
        char const * size = s.c_str();
        for(int i = 0; i < 1; i++)
        {
            qDebug() << "Written size bytes: " << clientConnection->write(size);
            qDebug() << "Size reported in textFortune is " << size;
            clientConnection->write(data);
        }
        qDebug() << "All data written? " << clientConnection->waitForBytesWritten();
        qDebug() << "Size is: " << size;
    }
    else
        qDebug() << "No connection";

并且接收字节看起来像

        int dataSize = 0;
        qDebug() << tcpSocket->read((char*)&dataSize, 2*sizeof(char));
        qDebug() << "Data size read from incoming is " << dataSize;
        buffer = tcpSocket->read(dataSize);
        qDebug() << "Current filling stand of buffer is: " << buffer.size();
        qDebug() << "Is my buffer empty?" << buffer.isEmpty();
        while(buffer.size() < dataSize) // only part of the message has been received
        {
            qDebug() << "Waiting for data!";
            counter++;
            tcpSocket->waitForReadyRead(); // alternatively, store the buffer and wait for the next readyRead()
            buffer.append(tcpSocket->read(dataSize - buffer.size())); // append the remaining bytes of the message
            if(counter == 1000)
                break;
            qDebug() << QString(buffer);
        }
        qDebug() << "Data is here";
        qDebug() << QString(buffer);

当传输响应为时

Written size bytes:  2
Size reported in textFortune is  57
All data written?  true
Size is:  57

答案是:

2
Data size read from incoming is  14133
Current filling stand of buffer is:  57
Is my buffer empty? false
Data is here

我的问题是正在读取的数据大小。为什么在这种情况下是14133,而不是57?是转换出错了,还是其他什么?

原因未知,通过更换解决问题

int dataSize = 0;
qDebug() << tcpSocket->read((char*)&dataSize, 2*sizeof(char));

char *dataS = new char[3];
dataS[2] = '';
int dataSize;
tcpSocket->read(dataS, 2*sizeof(char));
dataSize = atoi(dataS);