PDA

View Full Version : Having problems with getting QtpServer to Listen



weaver4
14th August 2012, 21:52
I have a real simple application where I want to have a TCP server running on Ubuntu 12.04. I have the following code:


WCServer server;
if (server.listen(QHostAddress::Any, 3912)) {
write("Able to listen on port: " + QString::number(server.serverPort()));
} else {
write("Failed to bind to port 3912.");
}
if (server.isListening()) {
write("Server is Listening on port " + QString::number(server.serverPort()));
} else {
write("Server is not Listening.");
}

WCServer is a subclass of QTcpServer here is the code for it.
WCServer.h:

#ifndef WCSERVER_H
#define WCSERVER_H

#include <QTcpServer>
#include "clientsocket.h"
#include "mainwindow.h"
#include "globals.h"

class WCServer : public QTcpServer
{
Q_OBJECT
public:
explicit WCServer(QObject *parent = 0);

private:
void incomingConnection(int socketID);
MainWindow *w;

signals:

public slots:

};

#endif // WCSERVER_H

This code runs and it say it is listening on port 3912, but when I use any of the following commands it does not show that that port is listening.

sockstat -l
netstat -lnptu

I checked with ufw and the firewall is not on.

I have tried to reach this port both locally and remotely but it always says "connection refused".

I have tried to run the program as sudo thinking "maybe a super user is the only one who can listen" but that makes no difference.

Any help would be greatly appreciated

weaver4
15th August 2012, 19:53
I found out I needed to use new and pass the parent. Odd.



server = new WCServer(this);
if (server->listen(QHostAddress::Any, 3912)) {
write("Able to listen on port: " + QString::number(server->serverPort()));
} else {
write("Failed to bind to port 3912.");
}
if (server->isListening()) {
write("Server is Listening on port " + QString::number(server->serverPort()));
} else {
write("Server is not Listening.");
}

yeye_olive
16th August 2012, 10:04
Is that really so stange? It is difficult for anyone to judge from a fragment of the code. I will try to guess from the information you made available. Since your new code mentions "this" on line 1, it means that it is part of a method's body. Therefore, in your original code, server would go out of scope at the end of the execution of this method and would be destroyed, effectively shutting the server down. The control would subsequently return to the event loop to wait for incoming connections but it was too late since the server had already been destroyed. Now that the server is allocated on the heap, it is not destroyed at the end of the method and this problem disappears. Alternatively you could allocate it on the stack somewhere where it lives long enough (e.g. in main()).

It would have been useful to see the whole code from the beginning.