QTcpServer not handling connections.
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:
Code:
#include <QObject>
Q_OBJECT
public:
Server();
bool done();
private slots:
void newConnection();
private:
bool d;
};
server.cpp:
Code:
#include "server.hpp"
#include <QTcpServer>
#include <QTcpSocket>
Server::Server() {
d = false;
connect(s,SIGNAL(newConnection()),
this,SLOT(newConnection()) );
}
bool Server::done() {
return d;
}
void Server::newConnection() {
qWarning() << "Got one.";
delete sock;
}
servermain.cpp:
Code:
#include "server.hpp"
int main() {
Server s;
while (!s.done()) {
}
return 0;
}
clientmain.cpp:
Code:
#include <QTcpSocket>
#include <iostream>
int main() {
char c;
while (std::cin >> c) {
switch(c) {
case 'c':
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.
Re: QTcpServer not handling connections.
123456 is probably an invalid port number. Try something smaller like 55555 for testing.
Re: QTcpServer not handling connections.
Well I feel kinda dumb for having an out-of-range port, but with that fixed the behaviour's the same.
Re: QTcpServer not handling connections.
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:
Code:
#include "server.hpp"
int main(int argc, char **argv)
{
Server s;
return app.exec();
}
Code:
#include <QTcpSocket>
#include <iostream>
int main(int argc, char **argv) {
char c;
while (std::cin >> c) {
switch(c) {
case 'c':
sock->connectToHost("127.0.0.1",123456);
if(sock->waitForConnected()) {
qWarning() << "OK";
}
else {
qWarning() << "NO";
}
delete sock;
};
}
return app.exec();
}
Re: QTcpServer not handling connections.
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.