Search code examples
qtsignalsqtcpsocketslotsqtcpserver

QTcpSocket readyRead() signal emits multiple times


I'm new to Qt and currently learning to code with QTcpServer and QTcpSocket.

My code to process data is like

Myclass() 
{
   connect(&socket, &QTcpSocket::readyRead, this, &MyClass::processData);
}

void MyClass::processData()
{
  /* Process the data which may be time-consuming */
}

Is it the correct way to use the signal like that? As I'm reading the documentation that in the same thread the slot is invoked immediately, which means if my processing work hasn't finished and new data comes, Qt will pause on the current work and enter the processData() again. That is not exactly what I want to do, So should I QueueConnection in the signal/slot connection?

Or could you please provide some good methods that I should adopt in this case?


Solution

  • Qt will not pause your current work when data comes in, it will call processData() only when the event loop is free and waiting for new events.

    so, when your application is busy executing your code, the application will appear to be unresponsive, because it can't respond to external events, so processData() won't get called if some data is received on the socket until the current function (that may contain your heavy code) returns, and the control is back in the event loop, that has to process the queued events (these events may contain the received data on the socket, or the user clicks on some QPushButton, etc) .

    in short, that's why you always have to make your code as short and optimized as possible, in order not to block the event loop for a long time.

    With the event delivery stuck, widgets won't update themselves (QPaintEvent objects will sit in the queue), no further interaction with widgets is possible (for the same reason), timers won't fire and networking communications will slow down and stop. Moreover, many window managers will detect that your application is not handling events any more and tell the user that your application isn't responding. That's why is so important to quickly react to events and return to the event loop as soon as possible!

    see https://wiki.qt.io/Threads_Events_QObjects