Reputation: 2358
I'm trying to create a TCP server in C++ with QT. I have the code but as soon as I try to connect to the server with SocketTest it says connection refused (most likely due to the server not running).
This is in my tcplistener.h:
#ifndef TCPLISTENER_H
#define TCPLISTENER_H
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QTcpServer>
class tcp_listener : public QTcpServer
{
Q_OBJECT
signals:
public slots:
void newConnectionFromServer()
{
QTcpSocket* newConnection = nextPendingConnection();
qDebug("New connection from %d", newConnection->peerAddress().toIPv4Address());
}
public:
tcp_listener(QObject *parent = 0)
: QTcpServer(parent)
{
listen(QHostAddress::Any, 30000);
connect(this, SIGNAL(newConnection()), SLOT(newConnectionFromServer()));
}
};
#endif // TCPLISTENER_H
This is in my engine.h:
#ifndef ENGINE_H
#define ENGINE_H
#include <QCoreApplication>
#include "tcplistener.h"
class engine
{
public:
void init()
{
qDebug("Initializing AuraEmu...");
tcp_listener list();
}
};
#endif // ENGINE_H
And this is my main.cpp:
#include <QCoreApplication>
#include "engine.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
engine eng = engine();
eng.init();
return a.exec();
}
Anybody know what the problem is?
Upvotes: 0
Views: 452
Reputation: 79467
The other answer, and my comment before that already cover what you did wrong, so I'll just supply the solution.
I've added comments because you said you come from Java and C#, but really, don't try to program C++ like it's Java or C#, because it's not.
class engine
{
public:
void init()
{
qDebug("Initializing AuraEmu...");
tcp_listener *list = new tcp_listener(); // Allocate on the heap instead of the stack.
}
~engine()
{
delete list; // C++ is an UNMANAGED language, there is no garbage collector
}
private:
tcp_listener *list; // This is a pointer to an object.
};
Upvotes: 1
Reputation: 9394
eng.init();
here you create
tcp_listener list();
and after eng.init() finished you detroy it, because it is object on stack.
Upvotes: 1