“无法将(null):: newConnection()连接到myserver :: onNewConnection()”-未调用newConnection信号

时间:2019-06-05 20:57:36

标签: c++ qt sockets server client

我试图在QT中运行简单的客户端服务器应用程序。问题在于服务器端的“连接”-未执行newConnection插槽,并且出现了异常(如标题中所示)。

*************** myserver.cpp ***********

#include "myserver.h"

myserver::myserver(){}
myserver::~myserver(){}

void myserver::startServer()
{
    qDebug()<<"Starting startServer()";
    tcpServer = new QTcpServer(this);
    if (this->listen(QHostAddress::Any,1000))
    {
        qDebug()<<"Listening";
    }
    else
    {
        qDebug()<<"Not listening";
    }
}

void myserver::incomingConnection(int socketDescriptor)
{
    qDebug()<<"incomingConnection() started";
    socket=new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));
    qDebug()<<socketDescriptor<<"Client connected";
}

void myserver::onNewConnection()
{
    qDebug()<<"onNewConnection() started";
}

********** myserver.h **************

#ifndef MYSERVER_H
#define MYSERVER_H

#include <QTcpServer>
#include <QTcpSocket>

class myserver: public QTcpServer
{
     Q_OBJECT

public:
    myserver();
    ~myserver();
    QTcpSocket* socket;
    QTcpServer *tcpServer=nullptr;

public slots:
    void startServer();
    void incomingConnection(int socketDescriptor);
    void onNewConnection();
};

#endif // MYSERVER_H

*********** testClient.cpp **************

#include "myclient.h"
#include "ui_myclient.h"

myclient::myclient(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::myclient)
{
    ui->setupUi(this);
    socket=new QTcpSocket(this);
    connect(socket,SIGNAL(connected()),this,SLOT(socketMap()));
}

myclient::~myclient()
{
    delete ui;
}

void myclient::on_pushButton_clicked()
{
    socket->connectToHost("127.0.0.1",1000);
    if(socket->isOpen())
    {
        qDebug()<<"Connected!";
    }
    else {
        qDebug()<<"Not connected";
    }
}

void myclient::socketMap()
{
    qDebug()<<"socketMap() started";
}

我希望在客户端连接时调用onNewConnection()。我还检查了客户端并确认了连接。

这是服务器上的控制台输出:

Starting startServer()
Listening
incomingConnection() started
948 Client connected

0 个答案:

没有答案