Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QUdpSocket not emiting readyRead in a multi files project
Qt 6.11 is out! See what's new in the release blog

QUdpSocket not emiting readyRead in a multi files project

Scheduled Pinned Locked Moved Unsolved General and Desktop
23 Posts 5 Posters 3.1k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • F febinaf

    @Christian-Ehrlicher
    I'm really getting into object oriented programming and pardon me if I'm asking a lot of silly questions.

    I'm trying to achieve what @jsulm mentioned as "Simply make it class member..." . I've created an object in the addUser.h private sections and got errors, that's the reason for trying out forward declaration.
    What I'm trying to obtain is, to make the signal readyRead() to be connected throughout the runtime, and the connect () is in the constructor of myUDP class.

    Christian EhrlicherC Online
    Christian EhrlicherC Online
    Christian Ehrlicher
    Lifetime Qt Champion
    wrote on last edited by
    #13

    @febinaf said in QUdpSocket not emiting readyRead in a multi files project:

    I've created an object in the addUser.h private sections and got errors

    Then please post the error messages. What you did wrong with the forward declared class was already explained...

    Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
    Visit the Qt Academy at https://academy.qt.io/catalog

    F 1 Reply Last reply
    0
    • Christian EhrlicherC Christian Ehrlicher

      @febinaf said in QUdpSocket not emiting readyRead in a multi files project:

      I've created an object in the addUser.h private sections and got errors

      Then please post the error messages. What you did wrong with the forward declared class was already explained...

      F Offline
      F Offline
      febinaf
      wrote on last edited by
      #14

      @Christian-Ehrlicher The error was that "the class name does not name a type" .. i think it was because of not including the required header files. Got that fixed now.

      Right now I've created an object in private section of addUser.h and then I'm calling a method from that object in between the addUser GUI. I'm using a debug message to get status of socket ->bind(), and it returns true as the window opens the addUser gui, and the same returns false when the sendUDP method is called inside the same window.
      Is this the reason for readyRead not being emitted.

      Christian EhrlicherC 1 Reply Last reply
      1
      • F febinaf

        @Christian-Ehrlicher The error was that "the class name does not name a type" .. i think it was because of not including the required header files. Got that fixed now.

        Right now I've created an object in private section of addUser.h and then I'm calling a method from that object in between the addUser GUI. I'm using a debug message to get status of socket ->bind(), and it returns true as the window opens the addUser gui, and the same returns false when the sendUDP method is called inside the same window.
        Is this the reason for readyRead not being emitted.

        Christian EhrlicherC Online
        Christian EhrlicherC Online
        Christian Ehrlicher
        Lifetime Qt Champion
        wrote on last edited by
        #15

        Please post a minimal, compilable exmaple to your problem - you did so many changes, posted only parts of your code so that I don't know what you are actually really compiling...

        Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
        Visit the Qt Academy at https://academy.qt.io/catalog

        F 1 Reply Last reply
        0
        • Christian EhrlicherC Christian Ehrlicher

          Please post a minimal, compilable exmaple to your problem - you did so many changes, posted only parts of your code so that I don't know what you are actually really compiling...

          F Offline
          F Offline
          febinaf
          wrote on last edited by
          #16

          @Christian-Ehrlicher Ok
          an on_pushButton_clicked from my mainwindow invokes an addUser object and shows the window.

          //addUser.h
          #ifndef ADDUSER_H
          #define ADDUSER_H
          #include <QMainWindow>
          #include <QDialog>
          #include <QString>
          #include <myudp.h>
          
          namespace Ui {
          class addUser;
          }
          class addUser : public QDialog
          {
              Q_OBJECT
          public:
              explicit addUser(QWidget *parent = nullptr);
              ~addUser();
              QString packetToDevice, IP, port;
              int portNum;
          
          private slots:
              void on_pushButton_2_clicked();
          
          private:
              Ui::addUser *ui;
              QString addUserName, addNewID, addRFID, confirmBuffer, strLength;
              myUDP myudp; //object added as member
          };
          
          #endif // ADDUSER_H
          
          //addUser.cpp
          #include "adduser.h"
          #include "ui_adduser.h"
          #include "QMessageBox"
          #include "QDebug"
          #include "myudp.h" //udp header
          
          //#include "QDeadlineTimer"
          
          addUser::addUser(QWidget *parent) :
              QDialog(parent),
              ui(new Ui::addUser)
          {
              ui->setupUi(this);
          }
          
          addUser::~addUser()
          {
              delete ui;
          }
          
          void addUser::on_pushButton_2_clicked() //submit button press
          {
              addUser User;
              QMessageBox mssgBox;
              addUserName = ui->lineEdit->text();
              addNewID = ui->lineEdit_2->text();
              addRFID = ui->lineEdit_3->text();
              IP = ui->lineEdit_4->text();
              port = ui->lineEdit_5->text();
              portNum = port.toInt();
          
              int rfidLength = addRFID.length();
              int lengthOfName = addUserName.length();
              strLength = QString::number(lengthOfName); // number to string
          
              if((rfidLength == 10) && (lengthOfName <11))
              {   mssgBox.setWindowTitle("Confirmation");
                  mssgBox.setText("Confirm the new user details" );
               
                  mssgBox.setStandardButtons(QMessageBox::Cancel | QMessageBox::Save);
                  int returnValue = mssgBox.exec();
          
          
                  switch(returnValue)
                  {
          
                      case QMessageBox::Save :
                          {
                          //packetize and send the details over UDP
                       packetToDevice = "FA"+addNewID+strLength+addUserName+addRFID;
                         myudp.udpSend(packetToDevice, IP, portNum); //UDP SEND Fn CALL
           User.show(); // back to the window
                          break;
                          }
                      case QMessageBox::Cancel :
                          User.show(); //back to window
                          break;
                      default:
                          qDebug()<<"entered default state";
                  }
          }
          
              else
              {
                  QMessageBox falseMssg;
                  falseMssg.setWindowTitle("Error");
                  falseMssg.setText("Invalid RFID/Name");
                 falseMssg.setStandardButtons(QMessageBox::Close);
                  falseMssg.exec();
                  User.show();
          
              }
          
          }
          

          the above one is the file where myudp object is to be used to send and readyRead should be emitted whenever datagram arrives.

          then the udp header and source is as follows:

          //myUdp.h
          #ifndef MYUDP_H
          #define MYUDP_H
          #include <QObject>
          #include <QUdpSocket>
          
          class myUDP : public QObject
          {
              Q_OBJECT
          public:
              explicit myUDP(QObject *parent = nullptr);
              void udpSend(QString, QString, int);
          signals:
          
          public slots:
              void receiveUDP();
          
          private:
              QUdpSocket *socket2;
          };
          
          #endif // MYUDP_H
          
          //myudp.cpp
          #include "myudp.h"
          #include "QUdpSocket"
          #include "QDebug"
          #include "adduser.h" //
          
          myUDP::myUDP(QObject *parent)
              : QObject{parent}
          {
              socket2 = new QUdpSocket(this);
              bool result = socket2->bind(QHostAddress::Any, 1234);
              qDebug()<<"bind status"<<result;
              connect(socket2, SIGNAL(readyRead()), this, SLOT(receiveUDP()));
             
          void myUDP::udpSend(QString a, QString ip, int port)
          {       const char *str;
                  QByteArray dataToSend;
                  dataToSend = a.toLatin1(); //Qstring to const char *
                  str = dataToSend.data();
                  int retVal = socket2 ->writeDatagram(str, QHostAddress(ip), port);
                  qDebug()<< retVal; // length of the transmitted string  if successfully transmitted or -1
          }
          
          void myUDP::receiveUDP() //called when readyRead SIGNAL is emitted.
          {
              while (socket2->hasPendingDatagrams())
              {
                  QByteArray datagram;
                  datagram.resize(socket2->pendingDatagramSize());
                  QHostAddress sender;
                  quint16 senderPort;
          
                  socket2->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort );
                  qDebug()<<datagram;
                  qDebug()<<"IP "<<sender.toString();
           }
          }
          
          Christian EhrlicherC J.HilkJ 2 Replies Last reply
          0
          • F febinaf

            @Christian-Ehrlicher Ok
            an on_pushButton_clicked from my mainwindow invokes an addUser object and shows the window.

            //addUser.h
            #ifndef ADDUSER_H
            #define ADDUSER_H
            #include <QMainWindow>
            #include <QDialog>
            #include <QString>
            #include <myudp.h>
            
            namespace Ui {
            class addUser;
            }
            class addUser : public QDialog
            {
                Q_OBJECT
            public:
                explicit addUser(QWidget *parent = nullptr);
                ~addUser();
                QString packetToDevice, IP, port;
                int portNum;
            
            private slots:
                void on_pushButton_2_clicked();
            
            private:
                Ui::addUser *ui;
                QString addUserName, addNewID, addRFID, confirmBuffer, strLength;
                myUDP myudp; //object added as member
            };
            
            #endif // ADDUSER_H
            
            //addUser.cpp
            #include "adduser.h"
            #include "ui_adduser.h"
            #include "QMessageBox"
            #include "QDebug"
            #include "myudp.h" //udp header
            
            //#include "QDeadlineTimer"
            
            addUser::addUser(QWidget *parent) :
                QDialog(parent),
                ui(new Ui::addUser)
            {
                ui->setupUi(this);
            }
            
            addUser::~addUser()
            {
                delete ui;
            }
            
            void addUser::on_pushButton_2_clicked() //submit button press
            {
                addUser User;
                QMessageBox mssgBox;
                addUserName = ui->lineEdit->text();
                addNewID = ui->lineEdit_2->text();
                addRFID = ui->lineEdit_3->text();
                IP = ui->lineEdit_4->text();
                port = ui->lineEdit_5->text();
                portNum = port.toInt();
            
                int rfidLength = addRFID.length();
                int lengthOfName = addUserName.length();
                strLength = QString::number(lengthOfName); // number to string
            
                if((rfidLength == 10) && (lengthOfName <11))
                {   mssgBox.setWindowTitle("Confirmation");
                    mssgBox.setText("Confirm the new user details" );
                 
                    mssgBox.setStandardButtons(QMessageBox::Cancel | QMessageBox::Save);
                    int returnValue = mssgBox.exec();
            
            
                    switch(returnValue)
                    {
            
                        case QMessageBox::Save :
                            {
                            //packetize and send the details over UDP
                         packetToDevice = "FA"+addNewID+strLength+addUserName+addRFID;
                           myudp.udpSend(packetToDevice, IP, portNum); //UDP SEND Fn CALL
             User.show(); // back to the window
                            break;
                            }
                        case QMessageBox::Cancel :
                            User.show(); //back to window
                            break;
                        default:
                            qDebug()<<"entered default state";
                    }
            }
            
                else
                {
                    QMessageBox falseMssg;
                    falseMssg.setWindowTitle("Error");
                    falseMssg.setText("Invalid RFID/Name");
                   falseMssg.setStandardButtons(QMessageBox::Close);
                    falseMssg.exec();
                    User.show();
            
                }
            
            }
            

            the above one is the file where myudp object is to be used to send and readyRead should be emitted whenever datagram arrives.

            then the udp header and source is as follows:

            //myUdp.h
            #ifndef MYUDP_H
            #define MYUDP_H
            #include <QObject>
            #include <QUdpSocket>
            
            class myUDP : public QObject
            {
                Q_OBJECT
            public:
                explicit myUDP(QObject *parent = nullptr);
                void udpSend(QString, QString, int);
            signals:
            
            public slots:
                void receiveUDP();
            
            private:
                QUdpSocket *socket2;
            };
            
            #endif // MYUDP_H
            
            //myudp.cpp
            #include "myudp.h"
            #include "QUdpSocket"
            #include "QDebug"
            #include "adduser.h" //
            
            myUDP::myUDP(QObject *parent)
                : QObject{parent}
            {
                socket2 = new QUdpSocket(this);
                bool result = socket2->bind(QHostAddress::Any, 1234);
                qDebug()<<"bind status"<<result;
                connect(socket2, SIGNAL(readyRead()), this, SLOT(receiveUDP()));
               
            void myUDP::udpSend(QString a, QString ip, int port)
            {       const char *str;
                    QByteArray dataToSend;
                    dataToSend = a.toLatin1(); //Qstring to const char *
                    str = dataToSend.data();
                    int retVal = socket2 ->writeDatagram(str, QHostAddress(ip), port);
                    qDebug()<< retVal; // length of the transmitted string  if successfully transmitted or -1
            }
            
            void myUDP::receiveUDP() //called when readyRead SIGNAL is emitted.
            {
                while (socket2->hasPendingDatagrams())
                {
                    QByteArray datagram;
                    datagram.resize(socket2->pendingDatagramSize());
                    QHostAddress sender;
                    quint16 senderPort;
            
                    socket2->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort );
                    qDebug()<<datagram;
                    qDebug()<<"IP "<<sender.toString();
             }
            }
            
            Christian EhrlicherC Online
            Christian EhrlicherC Online
            Christian Ehrlicher
            Lifetime Qt Champion
            wrote on last edited by
            #17

            I don't understand what you're doing - why do you try to send something to yourself? I doubt you receive data on the same socket you're currently writing it.

            Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
            Visit the Qt Academy at https://academy.qt.io/catalog

            F 1 Reply Last reply
            0
            • F febinaf

              @Christian-Ehrlicher Ok
              an on_pushButton_clicked from my mainwindow invokes an addUser object and shows the window.

              //addUser.h
              #ifndef ADDUSER_H
              #define ADDUSER_H
              #include <QMainWindow>
              #include <QDialog>
              #include <QString>
              #include <myudp.h>
              
              namespace Ui {
              class addUser;
              }
              class addUser : public QDialog
              {
                  Q_OBJECT
              public:
                  explicit addUser(QWidget *parent = nullptr);
                  ~addUser();
                  QString packetToDevice, IP, port;
                  int portNum;
              
              private slots:
                  void on_pushButton_2_clicked();
              
              private:
                  Ui::addUser *ui;
                  QString addUserName, addNewID, addRFID, confirmBuffer, strLength;
                  myUDP myudp; //object added as member
              };
              
              #endif // ADDUSER_H
              
              //addUser.cpp
              #include "adduser.h"
              #include "ui_adduser.h"
              #include "QMessageBox"
              #include "QDebug"
              #include "myudp.h" //udp header
              
              //#include "QDeadlineTimer"
              
              addUser::addUser(QWidget *parent) :
                  QDialog(parent),
                  ui(new Ui::addUser)
              {
                  ui->setupUi(this);
              }
              
              addUser::~addUser()
              {
                  delete ui;
              }
              
              void addUser::on_pushButton_2_clicked() //submit button press
              {
                  addUser User;
                  QMessageBox mssgBox;
                  addUserName = ui->lineEdit->text();
                  addNewID = ui->lineEdit_2->text();
                  addRFID = ui->lineEdit_3->text();
                  IP = ui->lineEdit_4->text();
                  port = ui->lineEdit_5->text();
                  portNum = port.toInt();
              
                  int rfidLength = addRFID.length();
                  int lengthOfName = addUserName.length();
                  strLength = QString::number(lengthOfName); // number to string
              
                  if((rfidLength == 10) && (lengthOfName <11))
                  {   mssgBox.setWindowTitle("Confirmation");
                      mssgBox.setText("Confirm the new user details" );
                   
                      mssgBox.setStandardButtons(QMessageBox::Cancel | QMessageBox::Save);
                      int returnValue = mssgBox.exec();
              
              
                      switch(returnValue)
                      {
              
                          case QMessageBox::Save :
                              {
                              //packetize and send the details over UDP
                           packetToDevice = "FA"+addNewID+strLength+addUserName+addRFID;
                             myudp.udpSend(packetToDevice, IP, portNum); //UDP SEND Fn CALL
               User.show(); // back to the window
                              break;
                              }
                          case QMessageBox::Cancel :
                              User.show(); //back to window
                              break;
                          default:
                              qDebug()<<"entered default state";
                      }
              }
              
                  else
                  {
                      QMessageBox falseMssg;
                      falseMssg.setWindowTitle("Error");
                      falseMssg.setText("Invalid RFID/Name");
                     falseMssg.setStandardButtons(QMessageBox::Close);
                      falseMssg.exec();
                      User.show();
              
                  }
              
              }
              

              the above one is the file where myudp object is to be used to send and readyRead should be emitted whenever datagram arrives.

              then the udp header and source is as follows:

              //myUdp.h
              #ifndef MYUDP_H
              #define MYUDP_H
              #include <QObject>
              #include <QUdpSocket>
              
              class myUDP : public QObject
              {
                  Q_OBJECT
              public:
                  explicit myUDP(QObject *parent = nullptr);
                  void udpSend(QString, QString, int);
              signals:
              
              public slots:
                  void receiveUDP();
              
              private:
                  QUdpSocket *socket2;
              };
              
              #endif // MYUDP_H
              
              //myudp.cpp
              #include "myudp.h"
              #include "QUdpSocket"
              #include "QDebug"
              #include "adduser.h" //
              
              myUDP::myUDP(QObject *parent)
                  : QObject{parent}
              {
                  socket2 = new QUdpSocket(this);
                  bool result = socket2->bind(QHostAddress::Any, 1234);
                  qDebug()<<"bind status"<<result;
                  connect(socket2, SIGNAL(readyRead()), this, SLOT(receiveUDP()));
                 
              void myUDP::udpSend(QString a, QString ip, int port)
              {       const char *str;
                      QByteArray dataToSend;
                      dataToSend = a.toLatin1(); //Qstring to const char *
                      str = dataToSend.data();
                      int retVal = socket2 ->writeDatagram(str, QHostAddress(ip), port);
                      qDebug()<< retVal; // length of the transmitted string  if successfully transmitted or -1
              }
              
              void myUDP::receiveUDP() //called when readyRead SIGNAL is emitted.
              {
                  while (socket2->hasPendingDatagrams())
                  {
                      QByteArray datagram;
                      datagram.resize(socket2->pendingDatagramSize());
                      QHostAddress sender;
                      quint16 senderPort;
              
                      socket2->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort );
                      qDebug()<<datagram;
                      qDebug()<<"IP "<<sender.toString();
               }
              }
              
              J.HilkJ Offline
              J.HilkJ Offline
              J.Hilk
              Moderators
              wrote on last edited by
              #18

              @febinaf I'm reasonably sure, that writeDatagram

              void myUDP::udpSend(QString a, QString ip, int port)
              {       const char *str;
                      QByteArray dataToSend;
                      dataToSend = a.toLatin1(); //Qstring to const char *
                      str = dataToSend.data();
                      int retVal = socket2 ->writeDatagram(str, QHostAddress(ip), port);
                      qDebug()<< retVal; // length of the transmitted string  if successfully transmitted or -1
              }
              

              is an asynchronous process. So there might be some lifetime issues...


              Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


              Q: What's that?
              A: It's blue light.
              Q: What does it do?
              A: It turns blue.

              F 1 Reply Last reply
              0
              • Christian EhrlicherC Christian Ehrlicher

                I don't understand what you're doing - why do you try to send something to yourself? I doubt you receive data on the same socket you're currently writing it.

                F Offline
                F Offline
                febinaf
                wrote on last edited by
                #19

                @Christian-Ehrlicher I'm writing data to IP and port entered using user input. And I've used the same socket to send and receive, as its being shown in online tutorials ..... https://www.youtube.com/watch?v=4qx4FaglSig

                I've checked the above code in another project with just main function and udp class, and both reading and writing works fine using a single socket.

                1 Reply Last reply
                0
                • J.HilkJ J.Hilk

                  @febinaf I'm reasonably sure, that writeDatagram

                  void myUDP::udpSend(QString a, QString ip, int port)
                  {       const char *str;
                          QByteArray dataToSend;
                          dataToSend = a.toLatin1(); //Qstring to const char *
                          str = dataToSend.data();
                          int retVal = socket2 ->writeDatagram(str, QHostAddress(ip), port);
                          qDebug()<< retVal; // length of the transmitted string  if successfully transmitted or -1
                  }
                  

                  is an asynchronous process. So there might be some lifetime issues...

                  F Offline
                  F Offline
                  febinaf
                  wrote on last edited by
                  #20

                  @J-Hilk ooh ... so the writeDatagram method may be killing the object after the methods execution?

                  Let me try with other write methods available in the QUdpSocket class.

                  Christian EhrlicherC 1 Reply Last reply
                  0
                  • F febinaf

                    @J-Hilk ooh ... so the writeDatagram method may be killing the object after the methods execution?

                    Let me try with other write methods available in the QUdpSocket class.

                    Christian EhrlicherC Online
                    Christian EhrlicherC Online
                    Christian Ehrlicher
                    Lifetime Qt Champion
                    wrote on last edited by
                    #21

                    @febinaf said in QUdpSocket not emiting readyRead in a multi files project:

                    so the writeDatagram method may be killing the object after the methods execution?

                    No

                    And I've used the same socket to send and receive, as its being shown in online tutorials ....

                    Yes, but in those cases the sender and receiver are different objects, not the same one!

                    Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                    Visit the Qt Academy at https://academy.qt.io/catalog

                    F 1 Reply Last reply
                    0
                    • Christian EhrlicherC Christian Ehrlicher

                      @febinaf said in QUdpSocket not emiting readyRead in a multi files project:

                      so the writeDatagram method may be killing the object after the methods execution?

                      No

                      And I've used the same socket to send and receive, as its being shown in online tutorials ....

                      Yes, but in those cases the sender and receiver are different objects, not the same one!

                      F Offline
                      F Offline
                      febinaf
                      wrote on last edited by
                      #22

                      @Christian-Ehrlicher on creating 2 different object for writing and reading, the first object creation gives the bind () status as true and when the object for write method is called, the bind() status is false.

                      Since the bind() is in the constructor of the class, creating new objects will execute the bind() method again and again, right?

                      Christian EhrlicherC 1 Reply Last reply
                      0
                      • F febinaf

                        @Christian-Ehrlicher on creating 2 different object for writing and reading, the first object creation gives the bind () status as true and when the object for write method is called, the bind() status is false.

                        Since the bind() is in the constructor of the class, creating new objects will execute the bind() method again and again, right?

                        Christian EhrlicherC Online
                        Christian EhrlicherC Online
                        Christian Ehrlicher
                        Lifetime Qt Champion
                        wrote on last edited by
                        #23

                        @febinaf said in QUdpSocket not emiting readyRead in a multi files project:

                        Since the bind() is in the constructor of the class, creating new objects will execute the bind() method again and again, right?

                        Then move it to somewhere else or simply create two QUdpSocket instances.

                        Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                        Visit the Qt Academy at https://academy.qt.io/catalog

                        1 Reply Last reply
                        1

                        • Login

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • Users
                        • Groups
                        • Search
                        • Get Qt Extensions
                        • Unsolved