QT下的线程问题,纠结死了。。。
废话不多说,代码先贴上!
这是共享的头文件
#ifndef LHT_GD_FORWARD_H
#define LHT_GD_FORWARD_H
class QtNetwork;
class QUrl;
class QFtp;
class QFile;
class QFileInfo;
#endif // LHT_GD_FORWARD_H
#ifndef LHT_GD_FTP_H
#define LHT_GD_FTP_H
#include <QThread>
#include "forward.h"
/*!
*ftp class
*/
class LFtp : public QThread
{
Q_OBJECT
public:
/*!
*function:默认构造函数
*descri:默认构造函数
*note:默认构造函数
*@param parent 是所有类的父类
*return:无
*/
explicit LFtp(QObject *parent = 0);
/*!
*function:下载单个文件
*descri:继续登陆ftp服务器并且下载文件
*note:无
*@param url 是下载文件的地址
*return:无
*/
void DownloadFile(const QUrl &m_url);
/*!
*function:下载更多的更新文件
*descri:调用DownloadFile()
*note:无
*@param:无
*return:无
*/
void Update();
/*!
*function:线程里的run函数
*descri:重载run函数
*note:无
*@param:无
*return:无
*/
void run();
signals:
/*!
*function:信号函数
*descri:当接受完文件后,触发Done()
*note:无
*@param:无
*return:无
*/
void ReceiveData();
public slots:
/*!
*function:信号槽
*descri:处理文件的函数
*note:无
*@param:error 是是否下载完成的标志
*return:无
*/
void Done(bool error);
private:
QFtp *m_Ftp; //Ftp指针
QFile *m_File; //File指针
};
#endif // LHT_GD_FTP_H
/*!
* Copyright (c) 2010 LandhightechInc. All rights reserved.
* Contact: liumao
* datetime:2013-06-19
* name:ftp.cpp
* function:download file from server
*/
#include "ftp.h"
#include <iostream>
using namespace std;
LFtp::LFtp(QObject *parent) :QThread(parent){
m_Ftp = new QFtp(this);
QObject::connect(m_Ftp,SIGNAL(ReceiveData(bool)), this, SLOT(Done(bool)),Qt::DirectConnection);
}
void LFtp::DownloadFile(const QUrl &m_url) {
QFileInfo fileInfo(m_url.path());
QString fileName = fileInfo.fileName();
m_File = new QFile(fileName);
if (!m_File->open(QIODevice::WriteOnly)) {
cerr << "Unable to save the file" << endl;
delete m_File;
m_File = 0;
return;
}
ftp->setTransferMode(QFtp::Passive);
ftp->connectToHost(m_url.host(), m_url.port(21));
ftp->login("anonymous","");
ftp->get(m_url.path(), m_File);
ftp->close();
emit ReceiveData();
}
void LFtp::Done(bool error) {
if (error) {
cerr << "Error: " << qPrintable(m_Ftp->errorString()) << endl;
} else {
cerr << "File downloaded as " << qPrintable(m_File->fileName())
<< endl;
}
m_File->close();
delete m_File;
m_File = 0;
}
void LFtp::run(){
Update();
}
void LFtp::Update(){
QUrl m_url("ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.10.tar.xz");
DownloadFile(m_url);
}
#include <QCoreApplication>
#include "ftp.h"
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
LFtp ftp;
ftp.start();
return app.exec();
}