Multiclient TCP server
-
Hello there,
I want to create a simple TCP server application that would handle multiple TCP clients. Normally I would create a separate thread for each connected client. In the past I have seen solutions concerning subclassing theQThread
like this one.But I feel like this is an obsolete and an overkill approach (I do not sublass
QThread
for a long time now). What would be the recommended modern Qt way of tackling this topic? Is usingQTcpServer
andQTcpClient
even the way to go, or is it unnecessarily to low level approach?I would appreciate all help.
-
hi @Bremenpl
In the past I have seen solutions concerning subclassing the QThread like this one.
But I feel like this is an obsolete and an overkill approach
it is, mostly born out of a convoluted documentation
Take a look at the threaded fortune server example
https://doc.qt.io/qt-5/qtnetwork-threadedfortuneserver-example.htmlshould get you started
-
@Bremenpl
you're right, I assumed it was updated 😡Well, how you're actually supposed to do it, is now in the documentation,
See the detailed description of the QThread class
https://doc.qt.io/qt-5/qthread.html#detailsThe first section
-
The only thing you have to take care when subclassing QThread is that the (possible) slots in your object derived from QThread are executed in the correct thread by moving the derived object into the thread. Otherwise there is no real difference.
-
@Bremenpl said in Multiclient TCP server:
Normally I would create a separate thread for each connected client
This is a myth. Follow @kshegunov 's link
-
1 client = 1 thread is actually unsustainable once the number of connected clients start increasing.
In the code linked to the chat example, both in the simple and advanced projects, you can easily see the clients are actually distributed amongQThread::idealThreadCount()
threads rather than having 1 per client.
It also only makes sense if there is some actual work to do in that secondary thread