我想通过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?是转换出错还是其他什么?
答案 0 :(得分:0)
原因未知,问题通过替换
解决了int dataSize = 0;
qDebug() << tcpSocket->read((char*)&dataSize, 2*sizeof(char));
到
char *dataS = new char[3];
dataS[2] = '\0';
int dataSize;
tcpSocket->read(dataS, 2*sizeof(char));
dataSize = atoi(dataS);