我尝试修改Qt
网络教程,并将其实现为:
quint16 blockSize;
void Client::readData()
{
qDebug() << "Received Data!";
QByteArray data;
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);
if (blockSize == 0) {
if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> blockSize;
}
qDebug() << "Received DATA II with blocksize " << blockSize;
if (tcpSocket->bytesAvailable() < blockSize)
{
qDebug() << tcpSocket->bytesAvailable() << ' ' << blockSize;
return;
}
qDebug() << "Received DATA III";
in >> data;
qDebug() << data;
QByteArray dbg = data; // create a copy to not alter the buffer itself
dbg.replace('\\', "\\\\"); // escape the backslash itself
dbg.replace('\0', "\\0"); // get rid of 0 characters
dbg.replace('\n', "\\n");
//dbg.replace('"', "\\\""); // more special characters as you like
qDebug() << dbg;
QString data_string(data);
qDebug() << "Emitting Signal";
emit Client::gotData(data_string);
}
void Server::sendData(void)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out << "Hello World, this is a very long text!";
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
qDebug() << "First number is: " << (quint16)(block.size() - sizeof(quint16));
qDebug() << "Blocksize is: " << block.size() << "with quint size: " << sizeof(quint16);
qDebug() << "Sending data!";
//Debug
QByteArray dbg = block; // create a copy to not alter the buffer itself
dbg.replace('\\', "\\\\"); // escape the backslash itself
dbg.replace('\0', "\\0"); // get rid of 0 characters
dbg.replace('\n', "\\n");
//dbg.replace('"', "\\\""); // more special characters as you like
qDebug() << dbg;
connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));
clientConnection->write(block);
//clientConnection->disconnectFromHost();
}
连接工作正常,但是当我调用sendData()
时,我得到(来自同一个函数)传输的块:
First number is: 43
Blocksize is: 45 with quint size: 2
Sending data!
"\0+\0\0\0'Hello World, this is a very long text!\0"
我的第一个问题是:\0
来自哪里?据我理解代码,首先我创建一个0
,然后我写文本,然后我回到前面并写出块的完整大小。是因为(quint16)
的大小?什么都不输入,我得到\0\0
,大小为0,这是正确的。上面示例的大小为43,对应于ascii中的+
(此符号也在上面的块中)。
我的第二个问题是:我的readData()
- 函数无法识别块大小(它总是返回450作为块大小,这显然是错误的)。为什么?我错过了什么吗?
更新:将QByteArray data;
更改为QString data;
后,我的问题消失了,我的代码中没有更奇怪的\0
- &gt;应该使用正确的数据类型 - &gt; 平视&GT;台