QTcpServer not working

QTcpServer not working

本文关键字:working not QTcpServer      更新时间:2023-10-16

我正试图用QT在C++中创建一个TCP服务器。我有代码,但当我尝试用SocketTest连接到服务器时,它说连接被拒绝(很可能是因为服务器没有运行(。

这是在我的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

这个在我的引擎里。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

这是我的主.cpp:

#include <QCoreApplication>
#include "engine.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    engine eng = engine();
    eng.init();
    return a.exec();
}

有人知道问题出在哪里吗?

另一个答案和我之前的评论已经涵盖了你做错了什么,所以我只提供解决方案。

我添加了注释,因为你说你来自Java和C#,但实际上,不要试图像编程Java或C#那样编程C++,因为它不是。

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.
};
eng.init();

在这里创建

 tcp_listener list();

在eng.int((完成后,您可以取消它的限制,因为它是堆栈上的对象。