Nat*_*han 5 c++ networking qt asynchronous
我想发出一系列网络请求(在 Qt 中),其中一个请求的详细信息取决于最后一个请求的结果。目前我的代码如下所示:
QNetworkReply *reply = m->get(QNetworkRequest(QUrl("http://qt-project.org")));
reply->connect(reply,&QNetworkReply::finished,[=](){
//Do something with reply, calculate a value for the next request
QNetworkReply *reply2 = m->get(QNetworkRequest(QUrl("http://www.google.de")));
reply->deleteLater();
reply2->connect(reply2,&QNetworkReply::finished,[=](){
//Do something with reply2, calculate a value for the next request
QNetworkReply *reply3 = m->get(QNetworkRequest(QUrl("http://amazon.de")));
reply2->deleteLater();
reply3->connect(reply3,&QNetworkReply::finished,[=](){
//...
});
});
});
Run Code Online (Sandbox Code Playgroud)
虽然这有效,但我看到了两个问题:
所以我正在寻找一种更好地构建这段代码的方法。我想到了以下选项:
(1)使用阻塞请求,可以简单写(伪代码!):
try {
ResultType res1 = blockingRequest("http://qt-project.org");
// Doe something with res1
ResultType res2 = blockingRequest("http://www.google.com");
// Doe something with res2
ResultType res3 = blockingRequest("http://amazon.de");
// Doe something with res3
catch(...) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
此代码必须在单独的线程中运行。我读到阻塞请求在 Qt 中很难做到,我更愿意坚持标准的 Qt 做事方式。
(2) 使用宏或其他一些机制来编写更好看的代码。我正在考虑haskell中的“do”语法。我之前在 Haxe 中使用MonadSurprise做过这个。在 Haxe 中使用这个我可以写:
MonadSurprise.dO({
res1 <= request("http://qt-project.org");
res2 <= request("http://www.google.de");
res3 <= request("http://amazon.de");
});
Run Code Online (Sandbox Code Playgroud)
MonadSurprise.dO 是一个宏,负责正确连接 Surprises(由请求返回)。它还通过停止完整操作并在发生错误时返回错误来处理错误。
但我不知道这样的事情是否可以在 c++/qt 中完成。