我寫了一個服務器/客戶端設置,可以來回發送字符串,它的工作原理。現在我試圖從一個不工作的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