PDA

View Full Version : waitForNewConnections doesn't block



KoosKoets
27th March 2007, 16:55
Hi folks,

I've some problems with the TcpServer::waitForNewConnections(int, bool&). Searching the archives or the net didn't help, so I hope somebody here can help me...

I made a small test program:


#include <QTcpServer>

int main ()
{
bool lConAvailable = true;
QTcpServer lServer;
QTcpSocket lSocket;

lSocket.connectToHost("172.16.140.32", 5000);
lServer.setSocketDescriptor(lSocket.socketDescript or());


while (true) {
if (lServer.waitForNewConnection(1000, &lConAvailable)) {
printf("\na Connection is available\n");
}
else {
printf(".");
fflush(stdout);
}
}
}

I expect this to block in the waitForNewConnection call for 1 second. As nothing is available there should be a print of a dot every seconds. This is not what happens: the dots are printed like crazy.

What I am doing wrong?

My .pro file looks like:


TEMPLATE = app
CONFIG += qt
TARGET = server
QT += network thread
SOURCES += main.cpp

high_flyer
27th March 2007, 17:05
I assume that the socket is looking at hasPendingConnections(), and waits the timeout period only if there are pending connections, if not, there is no need to wait, and it returns immidietly.
This is only a guess.

And plese use the code tags for code.

danadam
27th March 2007, 18:47
// cut
lSocket.connectToHost("172.16.140.32", 5000);
lServer.setSocketDescriptor(lSocket.socketDescript or());

while (true) {
if (lServer.waitForNewConnection(1000, &lConAvailable)) {
printf("\na Connection is available\n");
}
else {
printf(".");
fflush(stdout);
}
}
}

[...]
What I am doing wrong?

Hm... What to begin with ;) . Why do you connect to and then use the socket in server? Such socket is in a connected state and server require socket in a listening state to be able to accept incoming connections. You should use something like this:

if (!lServer.listen(QHostAddress::LocalHost, 5000)) {
printf("Failed to bind socket");
exit(1);
}

while (true) {
if (lServer.waitForNewConnection(1000, &lConAvailable)) {
printf("\na Connection is available\n");
}
else {
printf(".");
fflush(stdout);
}
}