我正在尝试使用QNetworkAccessManager进行多个请求,即使我连接插槽QNetworkAccessManager也无法发出finished()信号。
这是我实施的代码。
void GetNetwork::getAction(QStringList *urls, QList<QByteArray> *result)
{
uint size=urls->size();
multiGetResult=result;
getUrls=urls;
setFlags();
for(uint x=0;x<size;x++)
{
int test=caluculateIndex(x);
getNAM[test]->get(QNetworkRequest(QUrl(urls->at(x))));
}
//qDebug()<<reply->readAll();
while (!waitWithFlag()) QThread::msleep(15);
delete threadFlag;
}
bool GetNetwork::setMultipleGet(uint number)
{
int diff=number-(getNAM.size()-1);
if(((getNAM.size()-1)+diff)<0)
return false;
for(int i=0;i<diff;i++)
{
getNAM.append(new QNetworkAccessManager(this));
connect(getNAM[getNAM.size()-1],SIGNAL(finished(QNetworkReply*)),this,SLOT(handleMultiRequest(QNetworkReply*)));
}
for(int i=diff;i<0;i++)
{
disconnect(getNAM[getNAM.size()-1],SIGNAL(finished(QNetworkReply*)),this,SLOT(handleMultiRequest(QNetworkReply*)));
delete getNAM[getNAM.size()-1];
getNAM.remove(getNAM.size()-1);
}
return true;
}
void GetNetwork::handleMultiRequest(QNetworkReply * reply)
{
int index=getUrls->indexOf(reply->url().toString());
if(reply->error()!=QNetworkReply::NoError||index==-1)
{
QString error=QString("Network Error file:%1 line:%2 error:%3")
.arg(__FILE__)
.arg(__LINE__)
.arg(reply->errorString());
emit errorOccured(error);
return;
}
multiGetResult->insert(index,reply->readAll());
threadFlag[index]=true;
}
这些代码有什么问题?我无法弄明白。
谢谢。
答案 0 :(得分:1)
首先,您不需要为QNetworkAccessManager提供单独的线程,因为它自Qt 4.8.1起在内部运行在一个单独的线程(异步)中。
其次,您只是将QNetworkAccessManager的最后一个实例连接到已完成的插槽,而不是这样做,将每个QNetworkAccessManager实例与handleMultiRequest Slot连接,并在调用插槽时继续增加计数。你不需要睡觉和所有这些东西,它都是事件驱动的。 所以,
void GetNetwork::handleMultiRequest(QNetworkReply * reply)
{
int index=getUrls->indexOf(reply->url().toString());
if(reply->error()!=QNetworkReply::NoError||index==-1)
{
QString error=QString("Network Error file:%1 line:%2 error:%3")
.arg(__FILE__)
.arg(__LINE__)
.arg(reply->errorString());
emit errorOccured(error);
return;
}
count++;
if(count == num_get_requests)
{
emit
allDone()
}
}
答案 1 :(得分:0)
我改变了像Adnan想法的功能
void GetNetwork::handleMultiRequest(QNetworkReply * reply)
{
int index=getUrls->indexOf(reply->url().toString());
if(reply->error()!=QNetworkReply::NoError||index==-1)
{
QString error=QString("Network Error file:%1 line:%2 error:%3")
.arg(__FILE__)
.arg(__LINE__)
.arg(reply->errorString());
emit errorOccured(error);
return;
}
multiGetResult->insert(index,reply->readAll());
threadDoneCounter++;
if(threadDoneCounter==getUrls->size())
emit threadsAreDone();
}
和
void GetNetwork::getAction(QStringList *urls, QList<QByteArray> *result)
{
uint size=urls->size();
multiGetResult=result;
getUrls=urls;
threadDoneCounter=0;
for(uint x=0;x<size;x++)
{
int test=caluculateIndex(x);
getNAM[test]->get(QNetworkRequest(QUrl(urls->at(x))));
}
QEventLoop eLoop;
connect(this,SIGNAL(threadsAreDone()),&eLoop,SLOT(quit()));
eLoop.exec();
disconnect(this,SIGNAL(threadsAreDone()),&eLoop,SLOT(quit()));
}