我有 QTcpServer 的简单服务器和 QNetworkAccessManager 的简单客户端。
经过测试的Qt版本:
Wireshark屏幕截图:qt-wireshark.png
上部(带红线)是QNetworkAccessManager的结果,成功结果的最新数据包是curl尝试从QTcpServer获取数据
还有一个简单的示例来重现错误:testNetwork.zip
以下是客户端的示例代码:
void test(quint16 port)
{
QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest request;
request.setUrl(QUrl(QString("http://127.0.0.1:%1/").arg(port)));
manager->connect(manager, &QNetworkAccessManager::finished,
[](QNetworkReply *reply) {
qDebug() << QString("Finished. %1. %2").arg(reply->errorString()).arg(reply->error());
qDebug() << "readed: " << reply->readAll();
});
QNetworkReply *reply = manager->get(request);
reply->connect(reply, &QNetworkReply::readyRead, [reply]() {
qDebug() << QString("readyRead: '%1'").arg(QString(reply->readAll()));
});
}
和服务器:
QTcpSocket socket;
...
if(socket.waitForReadyRead(5000))
{
QByteArray request;
request += socket.readAll();
QByteArray responce("HELLO, WORLD! HELLO, WORLD! HELLO, WORLD! HELLO, WORLD!");
socket.write(responce);
if(!socket.waitForBytesWritten())
{
qWarning() << QString("Error occurred in waitForBytesWritten() method of the tcp socket. %1 (%2)")
.arg(socket.errorString())
.arg(socket.error());
}
}
else
{
qWarning() << QString("Error occurred in read method of the tcp socket. %1 (%2)")
.arg(socket.errorString())
.arg(socket.error());
}
我还在qt.io(QTBUG-56631)上创建了一个Bug报告
答案 0 :(得分:0)
您的客户端正在发出HTTP请求,但您的服务器不是http服务器 - 它不会发回有效的HTTP请求。
当您将客户端指向Web服务器时,您的客户端会正常工作,因为它是一个http服务器。
QByteArray responce("HELLO, WORLD! HELLO, WORLD! HELLO, WORLD! HELLO, WORLD!");
不是有效的HTTP响应。