qtService组件使用说明_第1页
qtService组件使用说明_第2页
qtService组件使用说明_第3页
qtService组件使用说明_第4页
qtService组件使用说明_第5页
已阅读5页,还剩9页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

qtService组件使用说明描述QtService组件可用于开发Windows服务和Unix守护进程。该项目提供的QtService模板类可用于实现服务应用程序,QtServiceController类可用于控制服务。在Windows系统用服务控制管理器实现。在Unix系统服务用守护进程实现。类说明:QtServiceControllerQtServiceController类提供了一组函数,可实现从另外的应用程序来安装和运行服务并查询、控制其执行状态。成员类型:enumQtServiceController::StartupType启动类型:常量值描述QtServiceController::AutoStartup0随系统启动自动启动。QtServiceController::ManualStartup1手动启动。仅用于Windows环境 成员函数:QtServiceController::QtServiceController(const

QString&name)创建指定名称服务的控制器。QtServiceController::〜QtServiceController()

[virtual]销毁服务控制器。boolQtServiceController::install(const

QString&serviceFilePath,constQString&account

=QString(),const

QString&password

=QString())

[static]为指定文件安装服务,如安装成功返回true,否则返回false。在Windows中使用给定的帐户和密码安装服务到服务控制管理器中。在Unix服务配置中,使用“QtSoftware”作为组织名称写入QSettings::SystemScope。帐户和密码参数被忽略。boolQtServiceController::isInstalled()const检测服务是否安装,如已安装则返回true;

否则返回false。boolQtServiceController::isRunning()const检测服务运行状态,正在运行则返回true;

否则返回false。boolQtServiceController::pause()暂停服务,成功暂停则返回true;

否则返回false。仅当服务状态为uint

category

=0,const

QByteArray&data

=QByteArray())写日志消息。message:消息内容id:消息标识符category:消息类别data:可以包含任意二进制数据。在Windows系统注册表中注册的消息文件要求必须提供消息字符串的id和category,参阅MSDN。voidQtServiceBase::pause()

[virtualprotected]暂停服务,虚函数需重新实现(如停止轮询计时器或忽略套接字通知程序)。voidQtServiceBase::processCommand(int

code)

[virtualprotected]处理用户命令代码,虚函数需重新实现。voidQtServiceBase::resume()

[virtualprotected]暂停服务后恢复,虚函数需重新实现。QString

QtServiceBase::serviceDescription()const返回服务的描述。QtServiceController::sendCommand()和QtService::processCommand()结合使用一个共享设置文件进行些简单的通信。注意:在Unix系统上,此类依赖于QtNetwork模块工具。使用示例:classMyService:publicQtService<QCoreApplication>{public:MyService(intargc,char**argv);~MyService();protected:voidstart();voidstop();voidpause();voidresume();voidprocessCommand(intcode);};intmain(intargc,char**argv){MyServiceservice(argc,argv);returnservice.exec();}使用QCoreApplication适用于没有GUI的服务,QApplication适用于有GUI的服务。需要通过重新实现QtServiceBase::start()函数来执行服务的核心工作。需要重新实现QtServiceBase::pause(),QtServiceBase::processCommand(),QtServiceBase::resume()和QtServiceBase::stop()等函数响应控制器干预服务的请求。exec()函数解析argv中传递的服务特定参数,执行所需的操作,然后退出。当argv中没有传递服务特定参数时,exec()将依次调用createApplication()、executeApplication()、start()函数后返回,此时服务启动等待服务控制器的命令。成员函数:QtService::QtService(int

argc,char**

argv,const

QString&name)构造名为name的服务对象。argc和argv中的参数在exec()函数解析后传递给应用程序的构造函数。在一个进程中只能有一个QtService对象。QtService::〜QtService()销毁服务对象。Application*QtService::application()const[protected]返回指向应用程序对象的指针。voidQtService::createApplication(int&argc,char**

argv)

[virtualprotected]创建应用程序类型的应用程序对象,将argc和argv传递给其构造函数,虚函数需重新实现。intQtService::executeApplication()

[virtualprotected]执行以前使用classInteractiveService:publicQtService<QApplication>{public:InteractiveService(intargc,char**argv);~InteractiveService();protected:voidstart();voidstop();voidpause();voidresume();voidprocessCommand(intcode);private:QLabel*gui;};InteractiveService::InteractiveService(intargc,char**argv):QtService<QApplication>(argc,argv,"QtInteractiveService"),gui(0){setServiceDescription("AQtservicewithuserinterface.");setServiceFlags(QtServiceBase::CanBeSuspended);}InteractiveService::~InteractiveService(){}voidInteractiveService::start(){#ifdefined(Q_OS_WIN)if((QSysInfo::WindowsVersion&QSysInfo::WV_NT_based)&&(QSysInfo::WindowsVersion>=QSysInfo::WV_VISTA)){logMessage("ServiceGUInotallowedonWindowsVista.Seethedocumentationforthisexampleformoreinformation.",QtServiceBase::Error);return;}#endifqApp->setQuitOnLastWindowClosed(false);gui=newQLabel("Service",0,Qt::WindowStaysOnTopHint|Qt::FramelessWindowHint);gui->move(QApplication::desktop()->availableGeometry().topLeft());gui->show();}voidInteractiveService::stop(){deletegui;}voidInteractiveService::pause(){if(gui)gui->hide();}voidInteractiveService::resume(){if(gui)gui->show();}voidInteractiveService::processCommand(intcode){gui->setText("Commandcode"+QString::number(code));gui->adjustSize();}intmain(intargc,char**argv){#if!defined(Q_WS_WIN)//QtService在SystemScope中存储服务设置,通常需要root权限。//要想用非root用户测试此例,需更改SystemScope设置文件中的目录QSettings::setPath(QSettings::NativeFormat,QSettings::SystemScope,QDir::tempPath());qWarning("(Exampleusesdummysettingsfile:%s/QtSoftware.conf)",QDir::tempPath().toLatin1().constData());#endifInteractiveServiceservice(argc,argv);returnservice.exec();}AsimpleHTTPServerHTTP服务器监听端口默认为8080。为每个GET请求返回一个简单的HTML页面后,关闭连接。classHttpDaemon:publicQTcpServer{Q_OBJECTpublic:HttpDaemon(quint16port,QObject*parent=0):QTcpServer(parent),disabled(false){listen(QHostAddress::Any,port);}voidincomingConnection(intsocket){if(disabled)return;//当一个新的客户端连接时,服务器构造一个QTcpSocket与客户端的通信。//由于QTcpSocket是异步工作的,这意味着所有的通信都是在readClient()和discardClient()两个槽中完成。QTcpSocket*s=newQTcpSocket(this);connect(s,SIGNAL(readyRead()),this,SLOT(readClient()));connect(s,SIGNAL(disconnected()),this,SLOT(discardClient()));s->setSocketDescriptor(socket);QtServiceBase::instance()->logMessage("NewConnection");}voidpause(){disabled=true;}voidresume(){disabled=false;}privateslots:voidreadClient(){if(disabled)return;//当客户端向服务器发送数据时调用此槽。//服务器发现若是GET请求,就返回一个非常简单的HTML文档。QTcpSocket*socket=(QTcpSocket*)sender();if(socket->canReadLine()){QStringListtokens=QString(socket->readLine()).split(QRegExp("[\r\n][\r\n]*"));if(tokens[0]=="GET"){QTextStreamos(socket);os.setAutoDetectUnicode(true);os<<"HTTP/1.0200Ok\r\n""Content-Type:text/html;charset=\"utf-8\"\r\n""\r\n""<h1>Nothingtoseehere</h1>\n"<<QDateTime::currentDateTime().toString()<<"\n";socket->close();QtServiceBase::instance()->logMessage("Wrotetoclient");if(socket->state()==QTcpSocket::UnconnectedState){deletesocket;QtServiceBase::instance()->logMessage("Connectionclosed");}}}}voiddiscardClient(){QTcpSocket*socket=(QTcpSocket*)sender();socket->deleteLater();QtServiceBase::instance()->logMessage("Connectionclosed");}private:booldisabled;};服务器使用了QtService::logMessage()函数将消息和状态报告发送到系统事件日志。服务器还支持暂停,暂停时忽略传入请求。该HttpService通过继承QtService类实现了后台服务功能。classHttpService:publicQtService<QCoreApplication>{public:HttpService(intargc,char**argv):QtService<QCoreApplication>(argc,argv,"QtHTTPDaemon"){setServiceDescription("AdummyHTTPserviceimplementedwithQt");setServiceFlags(QtServiceBase::CanBeSuspended);}由于服务不使用GUI,构造函数使用QCoreApplication进行初始化。构造函数的前两个参数将被传递给QtService,最后一个参数“QtHTTPDaemon”是服务名称。protected:voidstart(){QCoreApplication*app=application();quint16port=(app->argc()>1)?QString::fromLocal8Bit(app->argv()[1]).toUShort():8080;daemon=newHttpDaemon(port,app);if(!daemon->isListening()){logMessage(QString("Failedtobindtoport%1").arg(daemon->serverPort()),QtServiceBase::Error);app->quit();}}start()实现时首先检查参数是否是端口号port,是则使用,否则默认使用8080端口。然后使用new操作创建HTTP服务实例,将应用程序对象作为父对象,以确保应用退出时销毁HTTP服务对象。voidpause(){daemon->pause();}voidresume(){daemon->resume();}private:HttpDaemon*daemon;};Pause()和resume()的实现将请求转发到服务器对象。#include"main.moc"intmain(intargc,char**argv){#if!defined(Q_WS_WIN)//QtServicestoresservicesettingsinSystemScope,whichnormallyrequirerootprivileges.//Toallowtestingthisexampleasnon-root,wechangethedirectoryoftheSystemScopesettingsfile.QSettings::setPath(QSettings::NativeFormat,QSettings::SystemScope,QDir::tempPath());qWarning("(Exampleusesdummysettingsfile:%s/QtSoftware.conf)",QDir::tempPath().toLatin1().constData());#endifHttpServiceservice(argc,argv);returnservice.exec();}主入口函数创建服务对象,并使用exec()函数来执行服务。AnInteractiveService服务控制器通用命令行控制器可以安装和控制使用QtService组件编写的任何服务。它演示了如何使用QtServiceController类。注意事项:在Windows安装/卸载和启动/停止服务需要安全权限,可以管理员身份运行获取。#include<QtCore/QStringList>#include<QtCore/QDir>#include<QtCore/QSettings>#include"qtservice.h"intprocessArgs(intargc,char**argv){if(argc>2){QStringarg1(argv[1]);if(arg1==QLatin1String("-i")||arg1==QLatin1String("-install")){if(argc>2){QStringaccount;QStringpassword;QStringpath(argv[2]);if(argc>3)account=argv[3];if(argc>4)password=argv[4];printf("Theservice%sinstalled.\n",(QtServiceController::install(path,account,password)?"was":"wasnot"));return0;}}else{QStringserviceName(argv[1]);QtServiceControllercontroller(serviceName);QStringoption(argv[2]);if(option==QLatin1String("-u")||option==QLatin1String("-uninstall")){printf("Theservice\"%s\"%suninstalled.\n",controller.serviceName().toLatin1().constData(),(controller.uninstall()?"was":"wasnot"));return0;}elseif(option==QLatin1String("-s")||option==QLatin1String("-start")){QStringListargs;for(inti=3;i<argc;++i)args.append(QString::fromLocal8Bit(argv[i]));printf("Theservice\"%s\"%sstarted.\n",controller.serviceName().toLatin1().constData(),(controller.start(args)?"was":"wasnot"));return0;}elseif(option==QLatin1String("-t")||option==QLatin1String("-terminate")){printf("Theservice\"%s\"%sstopped.\n",controller.serviceName().toLatin1().constData(),(controller.stop()?"was":"wasnot"));return0;}elseif(option==QLatin1String("-p")||option==QLatin1String("-pause")){printf("Theservice\"%s\"%spaused.\n",controller.serviceName().toLatin1().constData(),(controller.pause()?"was":"wasnot"));return0;}elseif(option==QLatin1String("-r")||option==QLatin1String("-resume")){printf("Theservice\"%s\"%sresumed.\n",controller.serviceName().toLatin1().constData(),(controller.resume()?"was":"wasnot"));return0;}elseif(option==QLatin1String("-c")||option==QLatin1String("-command")){if(argc>3){QStringcodestr(argv[3]);intcode=codestr.toInt();printf("Thecommand%ssenttotheservice\"%s\".\n",(controller.sendCommand(code)?"was":"wasnot"),controller.serviceName().toLatin1().constData());return0;}}elseif(option==QLatin1String("-v")||option==QLatin1String("-version")){boolinstalled=controller.isInstalled();printf("Theservice\n""\t\"%s\"\n\n",controller.serviceName().toLatin1().constData());printf("is%s",(installed?"installed":"notinstalled"));printf("and%s\n\n",(controller.isRunning()?"running":"notrunning"));if(installed){printf("path:%s\n",controller.serviceFilePath().toLatin1().data());printf("description:%s\n",controller.serviceDescription().toLatin1().data());printf("startup:%s\n",controller.startupType()==QtServiceController::AutoStartup?"Auto":"Manual");}return0;}}}printf("controller[-iPATH|SERVICE_NAME[-

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论