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>
Q_OBJECT
public:
Server();
bool done();
private slots:
void newConnection();
private:
bool d;
};
#include <QObject>
class QTcpServer;
class Server : public QObject {
Q_OBJECT
public:
Server();
bool done();
private slots:
void newConnection();
private:
bool d;
QTcpServer * s;
};
To copy to clipboard, switch view to plain text mode
server.cpp:
#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;
}
#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;
}
To copy to clipboard, switch view to plain text mode
servermain.cpp:
#include "server.hpp"
int main() {
Server s;
while (!s.done()) {
}
return 0;
}
#include "server.hpp"
int main() {
Server s;
while (!s.done()) {
}
return 0;
}
To copy to clipboard, switch view to plain text mode
clientmain.cpp:
#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;
}
#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;
}
To copy to clipboard, switch view to plain text mode
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.
Bookmarks