I drilled the source code of the QtCore and QtNetwork modules.
Aperantly, QTcpServer can work in two modes: synchronous and asynchronous .
In synchronous mode, after calling listen() caller can call waitForNewConnection() , which is a blocking method (the thread will sleep until someone connects to the listening port). In this way, QTcpServer can run on stream without an event loop.
In asynchronous QTcpServer mode, the newConnection() signal will be emitted when a new connection is received. But in order to be able to do this, an event loop must be started. QCoreApplication based on QEventLoop and QAbstractEventDispatcher (abstract class, the specific type depends on the OS, for example QEventDispatcherUNIX ). This event manager can monitor socket conditions (represented by file descriptors). It has a registerSocketNotifier(QSocketNotifier*) method. This method is called by the constructor of the QSocketNotifier class, which QTcpServer creates an instance each time listen() called. The only system call that is called when QTcpServer::listen() is called is, of course, listen() , which returns immediately, all the real magic happens when the loop cycle starts. The event loop (using the dispatcher) will track if there is a specific condition for the sockets that have been registered. It calls the select() system call, which receives one or more file descriptors that will be monitored (by the kernel) for certain conditions (if there is data to read, if data can be written or if an error occurs). The call can block the flow until the conditions on the sockets are met, or it can return after a while, and the conditions on the sockets have not been met. I'm not sure if Qt calls select() with a given or missing wait time (to block indefinitely), I think it is defined in a complex way and mutable. Thus, when the condition on the socket was finally met, the event manager will notify QSocketNotifier for this socket, which will in tern notify QTcpServer , which is listening on the socket that will accept the connection, and emit a newConnection() signal.
Thus, QTcpServer itself is not called into the event / socket tracking system, but it depends on it through the QSocketNotifier , which it uses to asynchronously receive connections.
When the synchronous waitForNewConnection() method is waitForNewConnection() , it simply bypasses the entire contents of the QSocketNotifier and calls accept() , which blocks the stream until there is an incoming connection.
irpbc
source share