PDA

View Full Version : Networking: QTcpSocket timeout



weaver4
27th February 2010, 18:22
How can I change the connect timeout on a QTcpSocket? My application talks to other systems on the same subnet so I need to modify the timeout down to about 200ms.

caduel
27th February 2010, 19:43
does QAbstractSocket::waitForConnected() not do what you want?

weaver4
27th February 2010, 20:55
Do you know if waitForConnected() is blocking or does it call Application::ProcessEvents()?

squidge
27th February 2010, 22:00
It waits the specified amount of milliseconds before returning, so it's blocking.

weaver4
28th February 2010, 14:59
But while it is blocking it can make calls to qApp.ProcessMessages() to keep the GUI responsive. I wonder if it does that? I guess I will check.

squidge
28th February 2010, 15:21
I very much doubt it will do that. If you want that functionality, put it into a thread so you main gui thread continues to run.

weaver4
28th February 2010, 20:46
I found that it does not "refresh" the GUI.

Rather than introducing a new thread I wrote this routine that "refreshes" the GUI and returns true on connect and false on a timeout.



bool Connector::waitForConnection(quint16 ms)
{
QTime myTimer;
myTimer.start();
do {
qApp->processEvents();
if (tcpSocket.state() == QAbstractSocket::ConnectedState)
return true;
} while(myTimer.elapsed() < ms);
return false;
}


I could of used a QTimer and used the Connect SIGNAL but I was concerned about what could happen if I got a Connect SIGNAL at the same time that the Timer Exprires.

It would be simplest if the QTcpSocket had a timeout parameter; but that is where this thread started.

squidge
28th February 2010, 22:10
I hope your timeout is short, as your waitForConnection() method will use up 100% CPU usage until the timeout or the connection occurs. What would be better is to use an asynchronous function call - ie, as you said, a QTimer whilst waiting for the connect signal. You could of course check the connection state in your timer to just check if both signals occured at once, but the chance of that happening is slim.