PDA

View Full Version : QTcpServer not handling connections.



spraff
4th November 2008, 12:00
I've been having trouble getting my client/server code to work. Here's a little test program I put together to test my sanity.

server.hpp:

#include <QObject>
class QTcpServer;

class Server : public QObject {
Q_OBJECT
public:
Server();
bool done();
private slots:
void newConnection();
private:
bool d;
QTcpServer * s;
};

server.cpp:

#include "server.hpp"
#include <QTcpServer>
#include <QTcpSocket>

Server::Server() {
d = false;
s = new QTcpServer(this);
s->listen(QHostAddress::Any, 123456);
connect(s,SIGNAL(newConnection()),
this,SLOT(newConnection()) );
}

bool Server::done() {
return d;
}

void Server::newConnection() {
QTcpSocket * sock = s->nextPendingConnection();
qWarning() << "Got one.";
delete sock;
}

servermain.cpp:

#include "server.hpp"

int main() {
Server s;
while (!s.done()) {
}
return 0;
}

clientmain.cpp:


#include <QTcpSocket>
#include <iostream>

int main() {
char c;
QTcpSocket * sock;

while (std::cin >> c) {
switch(c) {
case 'c':
sock = new QTcpSocket();
sock->connectToHost("127.0.0.1",123456);
if(sock->waitForConnected()) {
qWarning() << "OK";
}
else {
qWarning() << "NO";
}
delete sock;
};
}
return 0;
}

If I fire up both programs in separate terminals, the client coughs out "OK" every time you enter a 'c', but the server never does anything, and in a debugger the newConnection slot is never executed. What's going on?

Thanks already.

caduel
4th November 2008, 12:52
123456 is probably an invalid port number. Try something smaller like 55555 for testing.

spraff
4th November 2008, 12:56
Well I feel kinda dumb for having an out-of-range port, but with that fixed the behaviour's the same.

pastor
4th November 2008, 13:03
2 spraff: If I don't miss my guess, the total number of network ports is 65534.

Do you have a firewall? May be, it blocked your connection?

//updated

Ahh, I looked at your code.

1) You don't use QCoreApplication (or QApplication) instance in your applications
2) It's bad idea to use infinity loop. Use qApp->quit() for that.

Try this code:


#include "server.hpp"

int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
Server s;
return app.exec();
}


#include <QTcpSocket>
#include <iostream>

int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
char c;
QTcpSocket * sock;

while (std::cin >> c) {
switch(c) {
case 'c':
sock = new QTcpSocket();
sock->connectToHost("127.0.0.1",123456);
if(sock->waitForConnected()) {
qWarning() << "OK";
}
else {
qWarning() << "NO";
}
delete sock;
};
}
return app.exec();
}

caduel
4th November 2008, 14:06
True... you do need a running QEventLoop for Qt to process network events and send you signals. So do put a QCoreApplication into your main() as suggested by prastor.