PDA

View Full Version : QLocalSocket, QThread and Signals



StarShaper
9th January 2012, 21:06
Hi,

I am writing a server with QLocalSocket. I'm experienced with C# and now I have some questions about Qt. If I write a QLocalServer with


Server::Server(QString servername, QObject *parent)
: QObject(parent), m_clients(NULL)
{
m_server = new QLocalServer(this);

if (!m_server->listen(servername)) {
qDebug() << "Not able to start the Server";
}

connect(m_server, SIGNAL(newConnection()), this, SLOT(socket_new_connection()));
}

and


void Server::socket_new_connection()
{
QLocalSocket *clientConnection = m_server->nextPendingConnection();

What about socket_new_connection()? The signal is emitted every time a new connection is available. There are a lot of signals available in QLocalServer and QLocalSocket, but if the network is busy, my UI will not respond, right?

I would like to call socket_new_connection() in a seperate thread. In C# you can write a BackgroundWorker, which starts listening in a seperate Thread.

How would I pass a new Connection to an seperate Thread in Qt?

Maybe it's better to create a Worker Thread (inherited from QThread) for every socket connection? :confused:

wysota
9th January 2012, 22:27
There are a lot of signals available in QLocalServer and QLocalSocket, but if the network is busy, my UI will not respond, right?
Why would it not respond?


I would like to call socket_new_connection() in a seperate thread.
There is no need to do that.


Maybe it's better to create a Worker Thread (inherited from QThread) for every socket connection? :confused:
No, there is no point in doing that since Qt handles networking asynchronously. If you had 10000 sockets open, I would agree you needed a couple of (10?) threads to handle all those sockets. Provided you could satitate them all with data.

StarShaper
10th January 2012, 01:34
No, there is no point in doing that since Qt handles networking asynchronously.

Thanks for this information!


Networking: all low-level Qt networking classes (QTcpSocket, QUdpSocket, QTcpServer, etc.) are asynchronous by design. When you call read(), they just return already available data; when you call write(), they schedule the writing for later. It’s only when you return to the event loop the actual reading/writing takes place. Notice that they do offer synchronous methods (the waitFor* family of methods), but their use is discouraged because they block the event loop while waiting. High-level classes, like QNetworkAccessManager, simply do not offer any synchronous API and require an event loop.

Then I only need to perform the computing in a separate thread. :)

wysota
10th January 2012, 02:08
Yes. I advise you to use QtConcurrent for this. Have a look at QRunnable and friends.

StarShaper
10th January 2012, 13:49
Thanks. I already found some nice Classes for my project, like QStateMachine. ;)