[SOLVED] QTcpSocket::readyRead() not emitted even with a running event loop
-
Hello,
I have an event loop running in the main thread, like this:
@
#include <QCoreApplication>
#include <thread>int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);Server *server = new Server; std::thread serverThread(&Server::run, server); serverThread.detach(); return a.exec();
}
@In the serverThread, I:
- create a QTcpServer,
- wait for a new connection,
- connect the QTcpSocket::readyRead() signal to a custom slot.
But for some reason, QTcpSocket::readyRead() is not emitted when new data is available.
However, when I put QTcpSocket::waitForReadyRead() right after the socket acceptance (QTcpServer::nextPendingConnection()), the signal is emitted.So I have two questions:
Is it because the event loop is running in the main thread and not in the thread in which the QTcpSocket object lives?
If so, why does calling QTcpSocket::waitForReadyRead() emit the signal?
Thank you.
-
Hi,
- Indeed, you have QThread that you can use for your purpose.
- Could be using an internal EventLoop somewhere
Anyway, why are you creating a secondary thread in this application ? It doesn't seem needed.
-
[quote author="SGaist" date="1410984725"]Hi,
- Indeed, you have QThread that you can use for your purpose.[/quote]I need to call QThread::exec() to actually start an event loop in that thread, right? Forcing me to subclass QThread as QThread::exec() is protected.
Otherwise I could use a QEventLoop I guess.
[quote author="SGaist" date="1410984725"]2. Could be using an internal EventLoop somewhere[/quote]Yes, probably...
[quote author="SGaist" date="1410984725"]Anyway, why are you creating a secondary thread in this application ? It doesn't seem needed.[/quote]The code above is just a minimalist example.
- Indeed, you have QThread that you can use for your purpose.[/quote]I need to call QThread::exec() to actually start an event loop in that thread, right? Forcing me to subclass QThread as QThread::exec() is protected.
-
Before subclassing, please take a look at the latest QThread documentation. You have there the explanation of the various techniques that you can use with QThread.
-
[quote author="SGaist" date="1411026277"]Before subclassing, please take a look at the latest QThread documentation. You have there the explanation of the various techniques that you can use with QThread.[/quote]Indeed the doc' states that "By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread."
I had a look at the "Blocking Fortune Client Example":http://qt-project.org/doc/qt-5/qtnetwork-blockingfortuneclient-example.html and they also call QTcpSocket::waitForReadyRead() before QTcpSocket::bytesAvailable().
I assume it's the right way to do it (along with using QThread) and that, as you said, it must process the events, maybe with an internal event loop.Thank you.