PDA

View Full Version : Multiple QNetworkAccessManager requests.



Diath
12th October 2011, 18:28
Hello QtCentre community. I wanted to make an application that would connect through proxy to several hosts and check which hosts have banished the proxy.
At first I thought of making an UI in Qt and connection checks in cURL but then I found out that Qt has QNetworkAccessManager so I decided to use this instead.
It actually works fine with one host - connects, waits for response, returns state. But if I run multiple checks from a loop it returns a state only once.
I thought of executing next "get()" in callback function after the first check is done, but I don't think it's correct solution.
Below I post my code, hopefully you guys can help me out with some solution.

checker.h:


QNetworkAccessManager *check[1024];


checker.cpp:


void Checker::test()
{
int count = ui->hosts->topLevelItemCount();
if(count == 0)
{
QMessageBox::information(this, "Info", "Hosts list is empty.");
return;
}

ui->progHosts->setMaximum(count);
ui->progHosts->setValue(0);

for(int i = 0; i < count; ++i)
{
QTreeWidgetItem *item = ui->hosts->topLevelItem(i);
check[i] = new QNetworkAccessManager;
check[i]->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, "somerandomproxy.org", 80));
check[i]->get(QNetworkRequest(QUrl(item->text(0))));
connect(check[i], SIGNAL(finished(QNetworkReply *)), this, SLOT(testCallback(QNetworkReply *)));
}
}

void Checker::testCallback(QNetworkReply *reply)
{
QTreeWidgetItem *item = ui->hosts->topLevelItem(1);
if(!item)
return;

if(reply->error())
{
item->setText(2, reply->errorString());
item->setTextColor(2, QColor(255, 0, 0));
}
else
{
item->setText(2, "OK");
item->setTextColor(2, QColor(0, 255, 0));
}
}

Cheers, Diath.

@Edit:
Never mind, I've got it fixed by connection the finished() slot to a QNetworkReply.

wysota
13th October 2011, 23:04
Note, you don't need separate network managers for each check, one is enough.