【发布时间】:2015-12-03 13:09:48
【问题描述】:
我编写了一个服务器/客户端设置,可以来回发送字符串并且它可以工作。现在我正试图从一个不起作用的 php 脚本发送数据,所以我试图解开它究竟为什么不起作用。
这是从客户端发送数据的代码,我发送到服务器的字符串 = "aa"
(注意代码中的 cmets)
void Client::sendNewMessage(){
qDebug() << "sendNewMessage()";
QString string(messageLineEdit->text());
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << quint16(0) << string; // why is the quint16 appended before the string?
out.device()->seek(0); // set current position to 0, why exactly?
out << (quint16)(block.size() - sizeof(quint16)); // substract 16bit unsigned int from the total data size?
//Probably something to do with the appending of the quint16 at the beginning.
tcpSocket->write(block);
}
这是服务器的读取功能:
void TcpServer::readIncomingData(){
QDataStream in(tcpServerConnection);
in.setVersion(QDataStream::Qt_4_0);
int size = (int) sizeof(quint16); // get packetsize? size = 2 because quint16 is 2 bytes?
qDebug() << "size = " << size;
// ** OPTIONAL CODE, WORKS WITHOUT ASWELL ** // I got this somewhere from the internet.
if (tcpServerConnection->bytesAvailable() < (int)sizeof(quint16))
return; // if size of packet is less than 2, return.
// Because there is not enough bytes to correctly read the data?
quint16 blockSize = 0;
in >> blockSize; // i noticed that after this line executes
// tcpServerConnection->bytesAvailable is substracted by 2
// and blockSize = 8 instead of 10, because
// tcpServerConnection->bytesAvailable starts with 10.
// it seems that the socket recognizes that a quint16 was appended
// before the actual data, hence the 8 bytes. Is this correct?
if (tcpServerConnection->bytesAvailable() < blockSize)
return;
QString data;
in >> data;
qDebug() << "data = " << data;
所以这些问题的主要目的是能够将数据从 PHP 脚本发送到服务器,所以我需要(并且想要)知道整个过程是如何工作的。如果有人能照亮这个黑洞,我会很高兴:D
注意服务器和客户端是使用 QTcpSocket 和 QTcpServer 编写的。
【问题讨论】:
-
套接字是顺序 I/O 设备,在它们上查找是无操作的。不要寻找他们!
-
... 但是您的代码中的第一次搜索是有效的。您正在寻找缓冲区,而不是套接字:)
-
@KubaOber aaah 是的,我已经从下面的 cmets 中得到了:D 谢谢!!