0

我刚刚开始为我的 Qt 应用程序实现一个 UDP 客户端。我按照这个例子。我能够向远程主机发送数据和从远程主机接收数据。这已在我的远程主机以及我正在为其开发此应用程序的本地客户端验证(通过从我的 main.cpp 调用 handleReadyRead() 在本地验证)。我似乎无法让 QUdpSocket 发出它的 readyRead 信号。这是为什么?

主文件

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QTimer>
#include "udpclient.h"


static double value = 0;
static bool flash = true;
static UDPClient client;



   
int update1000()
{
    QByteArray Data;
    Data.append((char) 0x00);
    Data.append((char) 0x2c);
    Data.append((char) 0x1a);
    Data.append((char) 0x2c);
    Data.append((char) 0x92);
    Data.append((char) 0xe6);
    Data.append((char) 0xf6);
    Data.append((char) 0xa0);
    client.SendPacket(Data);

    return 0;
}

int packetReady()
{
    qInfo() << "packetReady";
    return 0;
}



int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    qmlRegisterType<HorizontalBarGraph>("com.kubie.horizontalBarGraph", 1, 0, "HorizontalBarGraph");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    


    QObject *object = engine.rootObjects()[0];
   

    

    //qInfo() << "Initializing timer.";    
    QTimer timer1000;
    QObject::connect(&timer1000, &QTimer::timeout, update1000);
    timer1000.start(1000);



    return app.exec();
}

udpclient.h

#ifndef UDPCLIENT_H
#define UDPCLIENT_H


#include <QUdpSocket>

class UDPClient : public QObject
{
  Q_OBJECT

  public:
      explicit UDPClient(QObject *parent = nullptr);

      void SendPacket(const QByteArray &buffer);


  private:
      QUdpSocket *socket = nullptr;

  signals:

  public slots:
      void handleReadyRead();

};

#endif // UDPCLIENT_H

udpclient.cpp

#include "udpclient.h"

UDPClient::UDPClient(QObject *parent) :
    QObject(parent)
{
  socket = new QUdpSocket(this);

  //We need to bind the UDP socket to an address and a port
  //socket->bind(QHostAddress::LocalHost,1234);         //ex. Address localhost, port 1234
  socket->bind(QHostAddress::AnyIPv4,6969);         //ex. Address localhost, port 1234

  //connect(socket,SIGNAL(readyRead()),this,SLOT(handleReadyRead()));
  connect(socket, &QUdpSocket::readyRead, this, &UDPClient::handleReadyRead);

}


void UDPClient::SendPacket(const QByteArray &buffer)
{
    socket->writeDatagram(buffer, QHostAddress("192.168.174.10"), 6969);
}


void UDPClient::handleReadyRead()     //Read something
{
    qInfo() << socket->hasPendingDatagrams();

  QByteArray Buffer;
  Buffer.resize(socket->pendingDatagramSize());

  QHostAddress sender;
  quint16 senderPort;
  socket->readDatagram(Buffer.data(),Buffer.size(),&sender,&senderPort);
  qInfo() << Buffer;

  //The address will be sender.toString()
}
4

1 回答 1

0

QML 应用程序(至少)需要一个 QGuiApplication 才能运行。您将在命令行或 IDE 调试应用程序输出窗口中获得有关此的调试输出。要针对此类问题获得更致命的警告,您可以设置环境变量QT_FATAL_WARNINGS(有关更多信息,请参阅QDebug 文档)

于 2021-01-24T17:52:43.677 回答