gpt4 book ai didi

c++ - QTcpSocket 为什么接收到错误的数据?

转载 作者:行者123 更新时间:2023-11-28 07:32:35 25 4
gpt4 key购买 nike

我正在编写一个简单的网络应用程序。客户端发送到服务器消息服务器在 QTextEdit 中打印它并响应客户端。我正在使用 QTcpServer 和 QTcpSocket。有一个问题我无法解决。接收数据是 quint16 + QTime + QString,它作为 QByteArrey 发送。我使用 quint16 来接收数据 block 的大小。由于某种原因,当客户端发送到服务器时

next block size: 16 (quint16 value)
block size: 18

服务器获取:

next block size: 30073  (quint16 value)
block size: 18

如您所见,出于某种原因,服务器从 QDataStrem 获取了错误的变量值,它始终为 30073。我不明白为什么?

void Widget::slotSendToServer()
{
logTextEdit->append("slotSendToServer()");
QByteArray arrBlock;
QDataStream serverSendStream(&arrBlock, QIODevice::ReadWrite);
QString messageStr = messageLineEdit->text();

serverSendStream << quint16(0) << QTime::currentTime()
<< messageStr;

serverSendStream.device()->seek(0);
serverSendStream << (quint16)(arrBlock.size() - sizeof(quint16));

qDebug() << "next_block_size:"
<<(quint16)(arrBlock.size() - sizeof(quint16))
<< endl
<< "full size of Byte arrey:" << arrBlock.size();

tcpSocket->write(arrBlock);
messageLineEdit->clear();
}



void Widget::slotReadClient()
{
logTextEdit->append("slotReadClient()");
QTcpSocket *tcpSocket = (QTcpSocket*)sender();
QDataStream clientReadStream(tcpSocket);

while(true)
{
if (!next_block_size)
{
if (tcpSocket->bytesAvailable() < sizeof(quint16))
{
break;
}
clientReadStream >> next_block_size;
}

if (tcpSocket->bytesAvailable() < next_block_size)
{
break;
}
QTime time;
QString messageTextStr;
clientReadStream >> time >> messageTextStr;

QString messageCompleteStr =
time.toString() + " " + "Client has sent - "
+ messageTextStr;
logTextEdit->append("Message received: ");
logTextEdit->append(messageCompleteStr);

next_block_size = 0;

sendToClient(tcpSocket,
"Server Response: Received \""
+ messageTextStr + "\"");
}
}

最佳答案

您应该确保每次套接字连接时变量 next_block_size 都被初始化为 0。

如果您不重用相同的QTcpSocket 对象,这可以在您的Widget 类构造函数中完成,或者如果您这样做,在连接到信号的插槽中完成连接()

关于c++ - QTcpSocket 为什么接收到错误的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17381848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com