qt create Linux http请求协议如何实现多线程访问,不产生冲突,请举一个完整的例子
时间: 2024-04-07 16:31:43 浏览: 111
下面是一个完整的例子,演示了如何在Qt中使用多线程实现HTTP请求,并避免冲突:
```cpp
#include <QtNetwork>
#include <QThread>
#include <QDebug>
class HttpWorker : public QObject
{
Q_OBJECT
public:
HttpWorker(const QString& url, QObject* parent = nullptr)
: QObject(parent), m_url(url)
{}
public slots:
void start()
{
QNetworkAccessManager manager;
QNetworkRequest request(m_url);
QNetworkReply* reply = manager.get(request);
QEventLoop loop;
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (reply->error() == QNetworkReply::NoError) {
emit finished(reply->readAll());
} else {
emit error(reply->errorString());
}
reply->deleteLater();
}
signals:
void finished(const QByteArray& data);
void error(const QString& message);
private:
QString m_url;
};
class HttpThread : public QThread
{
Q_OBJECT
public:
HttpThread(const QString& url, QObject* parent = nullptr)
: QThread(parent), m_worker(url)
{}
void run() override
{
connect(&m_worker, &HttpWorker::finished, this, &HttpThread::onFinished);
connect(&m_worker, &HttpWorker::error, this, &HttpThread::onError);
m_worker.start();
}
signals:
void finished(const QByteArray& data);
void error(const QString& message);
private slots:
void onFinished(const QByteArray& data)
{
emit finished(data);
quit();
}
void onError(const QString& message)
{
emit error(message);
quit();
}
private:
HttpWorker m_worker;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
HttpThread thread1("https://www.baidu.com");
HttpThread thread2("https://www.google.com");
QObject::connect(&thread1, &HttpThread::finished, [&](const QByteArray& data){
qDebug() << "Thread 1 finished:" << data;
});
QObject::connect(&thread2, &HttpThread::finished, [&](const QByteArray& data){
qDebug() << "Thread 2 finished:" << data;
});
thread1.start();
thread2.start();
return a.exec();
}
#include "main.moc"
```
在该例子中,HttpWorker类用于发送HTTP请求和接收响应,HttpThread类用于在独立的线程中执行HttpWorker对象。在main函数中,创建了两个HttpThread对象,并分别发送HTTP请求。在HttpThread对象的finished信号被触发时,输出HTTP响应数据。
通过使用不同的HttpThread对象,可以在多个线程中同时发送HTTP请求,避免了多线程冲突问题。
阅读全文