Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QUdpSocket and readyRead signal



  • I have implemented a simple UDP server according the specifcations of QUdpSocket class (Qt 5.10.1).

    But on my code, the readySignal never received. I try to send data to the udp server via nc util: echo "Hello" | nc -u localhost 1234

    This is my code:

    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
    
        MyServer server;
        server.initSocket();
        return a.exec();
    }
    
    and MyServer class implementation:
    
    MyServer::MyServer(QObject *parent) : QObject(parent)
    {
    }
    
    void MyServer::initSocket()
    {
        udpSocket = new QUdpSocket(this);
        if(!udpSocket->bind(QHostAddress::Any, 1234, QAbstractSocket::BindFlag::ShareAddress))
          {
              qDebug() << "bind error";
          }
    
          if(udpSocket->state() == QUdpSocket::BoundState)
              qDebug() << "GREAT!!!";
    
        connect(udpSocket, SIGNAL(readyRead()),
                this, SLOT(readPendingDatagrams()));
    }
    
    void MyServer::readPendingDatagrams()
    {
        QByteArray Buffer;
        int bufSize = udpSocket->pendingDatagramSize();
        Buffer.resize(bufSize);
    
        QHostAddress sender;
        quint16 senderPort;
        udpSocket->readDatagram(Buffer.data(),Buffer.size(),&sender,&senderPort);
    
    }
    

    Any help would be appreciated.
    Thanks,
    IAE

    [Edit aha_1980: Fixed typo in title]



  • @iaguirre are you able to check your server is really listening on port 1234?

    $ netstat | grep 1234
    


  • I have finally resolved the problem by makig the connect before the bind process. Now, it works!!

    void MyServer::initSocket()
    {
        udpSocket = new QUdpSocket(this);
        connect(udpSocket, SIGNAL(readyRead()),
                this, SLOT(readPendingDatagrams()));
    
        if(!udpSocket->bind(QHostAddress::Any, 1234, QAbstractSocket::BindFlag::ShareAddress))
          {
              qDebug() << "bind error";
          }
    
          if(udpSocket->state() == QUdpSocket::BoundState)
              qDebug() << "GREAT!!!";
    
    }
    


  • Thank's a lot for sharing your workaround.. I've got same issue after updating my application from Qt 5.4.2 to 5.11.2!

    Performing connect to QUdpSocket::readyRead() signal before doing QUdpSocket::bind() also resolve it for me!

    Regards


Log in to reply