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