About debugging using VS
datased2019 opened this issue · comments
Hello. I am using QtService to act as a HttpServer. Compile perfectly fine. When I try debug using VS 2017. I could see the logs coming out and shows that onStart() is running. But I cannot connect to the port which HttpServer opend. BTW: It is running correctly using standard QtCoreApplication way.
Here is the code:
QtService::Service::CommandResult onStart() override {
qDebug() << Q_FUNC_INFO;
HttpPluginServer plugins{ "routes.json" };
HttpServer server;
HttpServerRequestRouter router{
{ QRegularExpression{""}, HttpFileServer::handler("public")},
{ QRegularExpression{""}, NotFoundHandler::handler()}
};
QObject::connect(&server, &HttpServer::requestReady,
&router, &HttpServerRequestRouter::handleRequest);
server.listen(QHostAddress::Any, 8080);
qDebug() << server.isListening(); // returns true
qDebug() << "Service was started";
return Synchronous; //service is now assumed started
}
int main(int argc, char* argv[]) {
TestService service{ argc, argv };
return service.exec();
}
Thx so much.
The reason for your problem is simple: Your server is going out of scope!
Unlike the Qt main, which blocks at a.exec()
, the onStart
is merely called to initialize the application and then exits. This means plugins
, server
and router
get destroyed at the end of the function.
To work around this problem, simply use pointers. I'd recommend making them member of the service like this:
// header
class MyService : public QtService::Service {
// ....
private:
HttpPluginServer *_plugins = nullptr;
HttpServer *_server = nullptr;
HttpServerRequestRouter *_router = nullptr;
};
// source
QtService::Service::CommandResult MyService::onStart() override {
qDebug() << Q_FUNC_INFO;
_plugins = new HttpPluginServer{ "routes.json" };
_server = new HttpServer{};
_router = new HttpServerRequestRouter {
{ QRegularExpression{""}, HttpFileServer::handler("public")},
{ QRegularExpression{""}, NotFoundHandler::handler()}
};
// ....
}
QtService::Service::CommandResult MyService::onStop(int &exitCode) override {
delete _router;
delete _server;
delete _plugins;
return Synchronous;
}
Note: If supported by HttpServer etc. you can also just construct them with the service as parent. Deleting in onStop
might not be neccessary, but you should at least "close" the server.
Great. It works now. Problem about the method lifecycle. :)
Really appreciate your quick reply.