我写了一个服务器/客户端设置,可以来回发送字符串,它的工作原理。现在我试图从一个不工作的PHP脚本发送数据,所以我试图解开为什么它不起作用。通过套接字发送数据的过程是如何工作的?
这是代码从客户端发送的数据,我发送到服务器=“AA”
(介意在代码中的注释)
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是的,我已经从下面的评论中得到:D谢谢! – CantThinkOfAnything