TcpSocket读取错误的数据
TcpSocket reads wrong data
我想通过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);
相关文章:
- 静态数据成员的问题-修复链接错误会导致编译器错误
- OpenCV C++ 3 维垫数据访问错误值
- 删除使数据处于"错误状态"的默认构造函数的模式?
- 数组数据以错误的方式遍历 Python/Matlab
- 在C 中获取Invalig使用非静态数据成员错误
- 非静态数据成员错误的使用无效
- 数据管理错误C++
- 是非静态数据成员错误的CPPReference定义
- 如何使用 C++ 驱动程序在 MongoDB 中使用 UserException 处理数据类型错误
- 通过ODBC发生数据截断错误
- FFmpeg:编码PCM 16音频数据分配错误
- 模板中的数据类型错误
- OpenCV 数据类型错误
- 喃喃自语/谷歌protobufs客户端读取数据函数错误
- 模板友元函数 C++ 中无效使用非静态数据成员错误
- PostgreSql查询参数数据类型错误
- c++数据结构错误的输出(链表)
- 在java中使用字符串来保存二进制数据是错误的
- 为什么在c++中,在矢量结束后插入数据是错误的
- libserial接收到的数据序列错误