Programm crashes when QTcpServer is called

杀马特。学长 韩版系。学妹 提交于 2019-12-08 04:02:39

问题


I'm trying a very, very simple QT networking program. For some reason it crashes when executing without any error message, since it's not printing out any of the outputs to the command line as expected. Here's the code:

qtTCPservertest.pro

QT       += core
QT       += network
QT       -= gui

TARGET   = qtTCPservertest
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app


SOURCES += main.cpp \
    theserver.cpp

HEADERS += \
    theserver.h

theServer.h

#ifndef THESERVER_H
#define THESERVER_H

#include <QTcpServer>
#include <stdio.h>


class theServer : public QTcpServer{
    Q_OBJECT
public:
    theServer();
    ~theServer();
    void goOnline();
};

#endif // THESERVER_H

theServer.cpp

#include "theserver.h"
theServer::theServer()
{
}

theServer::~theServer()
{
}

void theServer::goOnline()
{
       bool status = false;
       unsigned int portNum = 5200;

       status = this->listen(QHostAddress::Any, portNum );

       // Check, if the server did start correctly or not
       if( status == true )
           printf("Server up\n");
       else
           printf("Server down\n");
}

and the main.cpp

#include <QCoreApplication>
#include <stdio.h>
#include "theserver.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    printf("Test\n");
    theServer* aServer = new theServer();
    aServer->goOnline();
    aServer->~theServer();

    return a.exec();
}

Has anyone an idea, where I went wrong? Since there is no error I'm total clueless. It just doesn't print out anything, it just tells me to hit any key to close the window, as if it came to an end as usual.

Thanks for any advise.


回答1:


Here is the code that compiles and works for me (Qt 5.5):

TheServer.h

#ifndef THESERVER_H
#define THESERVER_H

#include <QTcpServer>

class TheServer : public QTcpServer
{
    Q_OBJECT
public:
    TheServer(QObject *pParent = nullptr);
    void goOnline();
};

#endif // THESERVER_H

TheServer.cpp

#include <QDebug>
#include "TheServer.h"

TheServer::TheServer(QObject *pParent)
    : QTcpServer(pParent)
{
}

void TheServer::goOnline()
{
    bool status = listen(QHostAddress::Any, 5200);

    if (status) {
        qDebug() << "Server up";
    } else {
        qDebug() << "Server down";
    }
}

main.cpp

#include <QCoreApplication>
#include "TheServer.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    TheServer server;
    server.goOnline();

    return a.exec();
}


来源:https://stackoverflow.com/questions/34270960/programm-crashes-when-qtcpserver-is-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!