我正在尝试用QT在C++中创建一个TCP服务器。我有代码,但是当我试图用SocketTest连接到服务器时,它说连接被拒绝了(很可能是因为服务器没有运行)。
这是在我的电子邮件里
#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这在我的引擎里
#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这是我的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();
}有人知道问题出在哪里吗?
发布于 2015-09-05 17:53:15
另一个答案是,在此之前我的评论已经涵盖了你做错了什么,所以我只提供解决方案。
我添加了评论,因为您说您来自于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.
};发布于 2015-09-05 17:08:07
eng.init();在这里你创造了
tcp_listener list();在eng.init()完成之后,您可以对其进行格式化,因为它是堆栈上的对象。
https://stackoverflow.com/questions/32415528
复制相似问题