Home > Software engineering >  The correct variant of implementation of the server-client in one application? Qt6
The correct variant of implementation of the server-client in one application? Qt6

Time:11-25

I am creating simple online chat with server and client in one application. I wrote client-side, but i don't know how will be correct use QTcpServer.

  1. Need i create QTcpServer in new thread? So that I can connect to it as a client from this application. If yes, how do it? Or it's useless and not needed idea?
  2. Need i create new thread for every new connection in order to process it?

I am developing a chat as a course project for a university

CodePudding user response:

Assuming you are using Qt's networking APIs, you don't need to use multiple threads. The reason is that Qt's APIs are designed around a non-blocking event-loop model, so it is expected that no function-call should ever take more than a negligible amount of time (e.g. a few milliseconds) to return, after which the main thread's QEventLoop resumes execution and can therefore handle other tasks in a timely manner, all from within a single thread.

That said, there are a few optional methods in the Qt API that are blocking, and in a single-threaded application, calling those methods risks making your application un-responsive for (however long it takes for those methods to return). Fortunately those methods aren't necessary, and they are clearly documented. I recommend avoiding them, as there are always better, non-blocking ways to achieve the same result in Qt, e.g. by connecting the appropriate signals to the appropriate slots.

To sum up: threads aren't necessary in Qt-based networking, and your program will be simpler, more reliable, and easier to debug if you don't use threads. When implementing server-like functionality, a QTcpServer object is useful; you might want to have a look at this example program for cues on how to use it.

  • Related