0

I'm trying to understand how QTcpSocket and QTcpServer works together. So I wrote this simple example, which starts server and client socket on localhost:

QTcpServer server;
qDebug() << "Listen: " << server.listen( QHostAddress::Any, 10590);

usleep( 500000); //1/2 sec

QTcpSocket client;
client.connectToHost( QHostAddress( "127.0.0.1"), 10590);

usleep( 5000000);
qDebug() << "Client socket available: " << client.isValid();
qDebug() << "Pending connections:" << server.hasPendingConnections();

And I got this output:

Listen:  true 
Client socket available:  true 
Pending connections false 

Why there is no pending connections?

PS> I don't wanna use SLOT/SIGNALS mechanism.

Valentin T.
  • 519
  • 3
  • 12

1 Answers1

1
int main( )
{
  QTcpServer server;
  qDebug() << "Listen: " << server.listen( QHostAddress::Any, 10590);

  usleep( 5000000);

  QTcpSocket client;
  client.connectToHost( QHostAddress( "127.0.0.1"), 10590);

  usleep( 5000000);

  qDebug() << "Client socket connected: " << ( client.state( ) == QTcpSocket::ConnectedState );
  qDebug() << "Pending connections:" << server.hasPendingConnections();
}

Output:

Listen:  true
Client socket connected:  false
Pending connections: false

This is because QTcpServer cannot answer to QTcpSocket query... both are on same thread and if QTcpSocket is executing, QTcpServer is on idle.

Try it in multi-thread app.

eferion
  • 872
  • 9
  • 14