Real example of multithreaded QHttpServer?
-
Hello, i tried to create multi-thread API for my apps, so my goal is to create multithreaded http server, with ability to process many route in the same time. I saw in doc this example:
server.route("/feature/", [] (int id) { return QtConcurrent::run([] () { return QHttpServerResponse("the future is coming"); }); });But in my opinion this doesn't work, like I want. I have created route with 5 sec msleep delay. But during the test I saw that second request is processing after when first will end. One positive i that GUI will no frezze.
Does anybody know, how to create real multithread http server? My Qt is 6.5.3. Maybe using QThread or QThreadPool?
-
Hello, i tried to create multi-thread API for my apps, so my goal is to create multithreaded http server, with ability to process many route in the same time. I saw in doc this example:
server.route("/feature/", [] (int id) { return QtConcurrent::run([] () { return QHttpServerResponse("the future is coming"); }); });But in my opinion this doesn't work, like I want. I have created route with 5 sec msleep delay. But during the test I saw that second request is processing after when first will end. One positive i that GUI will no frezze.
Does anybody know, how to create real multithread http server? My Qt is 6.5.3. Maybe using QThread or QThreadPool?
This code:
#include <QCoreApplication> #include <QTcpServer> #include <QHttpServer> #include <QtConcurrent> #include <QDebug> QHttpServerResponse handleRequest(int id) { qDebug() << "Start" << id << QThread::currentThread(); QThread::sleep(5); qDebug() << "Finish" << id; return QHttpServerResponse("response text\n"); } int main(int argc, char **argv) { QCoreApplication app(argc, argv); QHttpServer server; server.route("/", [] (int id) { return QtConcurrent::run(&handleRequest, id); }); auto tcpserver = new QTcpServer(qApp); if (!tcpserver->listen(QHostAddress::Any, 30000) || !server.bind(tcpserver)) { return -1; } qDebug() << "Listening on port" << tcpserver->serverPort(); return app.exec(); }Produces results like this:
./test Listening on port 30000 Start 0 QThreadPoolThread(0x5d512f61d580, name = "Thread (pooled)") Start 2 QThreadPoolThread(0x5d512f8b6400, name = "Thread (pooled)") Start 1 QThreadPoolThread(0x5d512f62ecb0, name = "Thread (pooled)") Start 4 QThreadPoolThread(0x5d512f630430, name = "Thread (pooled)") Start 3 QThreadPoolThread(0x5d512f8b6ce0, name = "Thread (pooled)") Finish 0 Finish 4 Finish 1 Finish 2 Finish 3 ^Cwhen tested with:
curl -o - http://localhost:30000/0 & curl -o - http://localhost:30000/1 & curl -o - http://localhost:30000/2 & curl -o - http://localhost:30000/3 & curl -o - http://localhost:30000/4 &Request processing is interleaved, multi-threaded. The size of the thread pool is limited so more requests will start waiting. Using
curl --parallelchanges the behaviour with respect to the first request curl sends. -
A apaczenko1993 has marked this topic as solved on