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

QUdpSocket receive Datagram into QtConcurrent



  • Hello everyone,

    Still learning on Qt, and I try to run a QUdpSocket receiving UDP data into a QtConcurrent thread, for avoiding GUI freezing.

    Here my main.cpp

    If i call "testComThread()" my function work and I receive my data, but if i call "QtConcurrent::run(testComThread);" I dont see any data into my console and my breakpoint in my "while" is never reached.

    Did I need to call a kind of dispatcher or something maybe? This is my first use of QtConcurrent. Thanks in advance.

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <Manage/variablesglobales.h>
    #include <Manage/communications.h>
    #include <QtConcurrent>
    
    void testComThread();
    
    int main(int argc, char *argv[])
    {
    #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    #endif
    
        QGuiApplication app(argc, argv);
    
        QQmlApplicationEngine engine;
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                         &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
        engine.load(url);
    
    
        QFuture<void> test1 = QtConcurrent::run(testComThread);
        //testComThread();
    
    
        return app.exec();
    }
    
    void testComThread()
    {
        Communications* com = new Communications();
        com->InitialiseConnection();
    }
    

    my communication.cpp

    #include "communications.h"
    
    Communications::Communications(QObject *parent) : QObject(parent)
    {
    
    }
    
    void Communications::InitialiseConnection()
    {
        udpSock = new QUdpSocket(this);
        udpSock->bind(QHostAddress::Any,50003);
    
       connect(udpSock,&QUdpSocket::readyRead,this,&Communications::ReceiveUdpPackage);
    }
    
    void Communications::ReceiveUdpPackage()
    {
        QHostAddress sender;
        quint16  port;
    
        while (udpSock->hasPendingDatagrams())
        {
            QByteArray datagram;
            datagram.resize(udpSock->pendingDatagramSize());
            udpSock->readDatagram(datagram.data(),datagram.size(),&sender,&port);
            qDebug() <<"Message From :" << datagram.data();
        }
    }
    

    Thank you in advance.



  • @LudoFR
    I said earlier I don't know where your window is freezing. Let's find out whether ReceiveUdpPackage() is being run thousands of times per second? Comment out your qDebug() for each datagram, we don't want thousands per seconds debug output. Put in a member variable to count the total number of times and debug it out occasionally. Are we indeed talking about thousands per second?



  • @LudoFR said in QUdpSocket receive Datagram into QtConcurrent:

    I try to run a QUdpSocket receiving UDP data into a QtConcurrent thread, for avoiding GUI freezing.

    I know nothing about QML. But why are using any threads here? The GUI does not freeze when you execute UDP/TCP calls because in Qt they are asynchronous, they do not block the UI but rather you pick up the call completion in a slot. It may or may not apply to you, but nearly every beginner here starts out wanting to use threads when you don't need to with Qt.



  • @JonB Wow ok thanks,

    Well I have try to move my window and its a bit laggy for one second but, yea, the windows is not totally freezed... Is not really smooth like if I don't run the communication but its ok for a start.

    You told me you don't really know about QML, but if I want to change a value into a component of my GUI, what is the best way? If I remember, before use Qt, I have read somewhere online Qt have a kind of DataBinding.

    @JonB said in QUdpSocket receive Datagram into QtConcurrent:

    It may or may not apply to you, but nearly every beginner here starts out wanting to use threads when you don't need to with Qt.

    Haha, yes it is... Always the first thing i try in a new language.. Threading... But that a good point of Qt, I was so afraid about Qt and C++ but that kind of information confort me..



  • Mean while i wrinting my previous answer... my GUI is freezed, i can move the windows but "Not responding" and cant resize for an example..
    Screenshot 2021-10-03 122614.png



  • @LudoFR
    Where are you in your code when this happens? Like I said, I don't know if there is anything special in QML. But in principle the code you have written looks right to me for non-blocking: you connect() the QUdpSocket::readyRead() signal to your slot which only reads datagrams while (udpSock->hasPendingDatagrams()), then it should exit and the Ui become responsive again. How many times do you see qDebug() <<"Message From :" << datagram.data();? Put a qDebug() at the end of the slot so we know it has exited.



  • First, thanks for your anwser.

    Well in fact the goal is to get data read from joysticks and I/O cards, this "while" is infinite until the program is closed.

    Between 4 and 8 hours (work time).

    I have add a counter in my C# udp sender function and I send 131225 time in 10 seconds. Its a lot I know but in this data, some value like "Emergency button" need to be get really fast. Do you think this is the problem ?

    I don't know if that can help but here my C# sender function : (Function just created for my Qt training)

        public partial class MainWindow : Window
        {
            int counter = 0;
            public MainWindow()
            {
                InitializeComponent();
    
                Timer time = new Timer(10000);
                time.Elapsed += Time_Elapsed;
    
                Task.Run(() =>
                {
                    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.14"), 50003);
                    time.Start();
                    while (true)
                    {
                        byte[] datas;
                        string p = string.Empty;
                        Dispatcher.Invoke(() => { p = txt_textbox.Text; });
    
                        datas = Encoding.UTF8.GetBytes(p);
                        s.SendTo(datas, ep);
                        counter++;
                    }
                });
            }
    
            private void Time_Elapsed(object sender, ElapsedEventArgs e)
            {
                MessageBox.Show(counter.ToString());
            }
        }
    


  • @LudoFR
    You do not seem to have done anything about determining where your QML UI client is unresponsive.

    I send 131225 time in 10 seconds

    If you mean your client may be executing ReceiveUdpPackage(), or receiving datagrams inside it, 13 thousand times per second I imagine that might be problem.



  • @JonB said in QUdpSocket receive Datagram into QtConcurrent:

    If you mean your client may be executing ReceiveUdpPackage(), or receiving datagrams inside it, 13 thousand times per second I imagine that might be problem.

    In C# is work really good, so do you think this amount of data is too much?

    But is for Qt not for c++ who is apparently more efficient than C#? My IDE is also in pain, its hard to put a breakpoint because my IDE is laggy and almost freezed too !!


  • Lifetime Qt Champion

    Then use C# ...



  • @Christian-Ehrlicher Wow, thank for this answer, really appreciate champ.

    @JonB Seems to be really better if I do not run in Debug, not a surprise.. the console take like 3/4 seconds for beeing updated, but after some test with breakpoint, the console look to take long time to print but the value receive look good apprently..


  • Lifetime Qt Champion

    You just blame about something, @JonB tells you that you should try to reduce the data rate to see if it helps (which I doubt - there is another problem somewhere in your app) and you start complaining about your IDE just to blame Qt again. This is nothing more than trolling for me.

    The normal way here is to reduce the program until the error/problem goes away and/or others can reproduce it. Daily programmers work.



  • Listen champ,

    In my country, and almost all country around Earth I think, question mark,

    @LudoFR said in QUdpSocket receive Datagram into QtConcurrent:

    But is for Qt not for c++ who is apparently more efficient than C#?

    Is for asking a question, not for blaming or something.

    Yea I have reduce the amount of data with a 50ms delay... but whatever you don't care by having deduction without asking if the result is better..

    Complaining? No, just tryin to understand, I'm sorry if I hurt you by asking question performance about your IDE (baby, life or anything it is for you), but for me its a tool... yea a tool.. with pros and cons I'm sure, but if you told me Qt are only pros, so do not loose your time to answer me because you can't be objective to me.

    I want make you happy, in C# and visual studio (yea Microsoft, pretty sure you like according to your avatar) well console is slow in Debug mode when you use it roughly..

    Qt has to stay free or it will die.
    I'm sure your help Qt with your kind of answers champ.

    Here, now you have your troll.


  • Lifetime Qt Champion

    @LudoFR said in QUdpSocket receive Datagram into QtConcurrent:

    your IDE

    It's not my IDE - I did not even contributed a single line to QtCreator. I'm using mostly MSVC for debugging because gdb and cdb (not QtCreator) are painful slow. Blaming an IDE for this is nonsense. And btw: Qt != QtCreator.



  • @LudoFR
    I said earlier I don't know where your window is freezing. Let's find out whether ReceiveUdpPackage() is being run thousands of times per second? Comment out your qDebug() for each datagram, we don't want thousands per seconds debug output. Put in a member variable to count the total number of times and debug it out occasionally. Are we indeed talking about thousands per second?


  • Lifetime Qt Champion

    @JonB said in QUdpSocket receive Datagram into QtConcurrent:

    Comment out your qDebug() for each datagram

    correct - printing so much data to the windows console will not work, no matter if it's C++, C#, Java or whatever. The windows console is painful slow.



  • @JonB Thanks again for your help, well its seems your right, without qDebug(), my GUI is not freezed, I have try with a delay of 50 and 100ms.

    I will be careful next time with how I use the qDebug(), good to know.

    Didn't think about that because never has any problem with my console output who usually are really fast. (Used only for debuging of course).

    Now I will try Databing in my GUI and IO cards communication for check if this 50/100ms delay do not affect smoothest for our drivers.

    Thanks a lot @JonB for your help, your professionalism and all this informations.



  • @LudoFR
    I am interested to learn: if you have put it some counter for each datagram received instead, are you indeed seeing 13,000-odd per second?



  • @JonB

    For one second exactly (No delay) :

    QT receive counter : 4602.
    VS sender counter : 4565

    For 10 seconds exactly (No delay):

    QT : 129278
    VS: 129234



  • @LudoFR
    You don't really need a timer. This will do, presumably:

            udpSock->readDatagram(datagram.data(),datagram.size(),&sender,&port);
            memberCounter++;
            if (memberCounter % 10000 == 0)
                qDebug() <<"memberCounter:" << memberCounter;
    


  • @LudoFR
    Well, firstly looks like VS & Qt are similar, which is good news. Secondly surprised it seems receiver is receiving more than sent? I don't think each side agrees on exactly what 1 second is :D



  • @JonB said in QUdpSocket receive Datagram into QtConcurrent:

    Secondly surprised it seems receiver is receiving more than sent?

    @JonB Thanks god I'm not the only one...

    @JonB said in QUdpSocket receive Datagram into QtConcurrent:

    I don't think each side agrees on exactly what 1 second is :D

    Science....is not an exact science... did performance computer impact that kind of information? Sender is an Asus Rog Strix3 with a config lower than my PC



  • @LudoFR said in QUdpSocket receive Datagram into QtConcurrent:

    Hello everyone,

    Still learning on Qt, and I try to run a QUdpSocket receiving UDP data into a QtConcurrent thread, for avoiding GUI freezing.

    Here my main.cpp

    If i call "testComThread()" my function work and I receive my data, but if i call "QtConcurrent::run(testComThread);" I dont see any data into my console and my breakpoint in my "while" is never reached.

    Did I need to call a kind of dispatcher or something maybe? This is my first use of QtConcurrent. Thanks in advance.

    Truncated code:

    int main(int argc, char *argv[])
    {
        QFuture<void> test1 = QtConcurrent::run(testComThread);
        return app.exec();
    }
    
    void testComThread()
    {
        Communications* com = new Communications();
        com->InitialiseConnection();
    
        udpSock = new QUdpSocket(com);
        udpSock->bind(QHostAddress::Any,50003);
    
        connect(udpSock,&QUdpSocket::readyRead,this,&Communications::ReceiveUdpPackage);
    }
    

    This won't work. QtConcurrent::run() runs a function in a thread that doesn't have an event loop, and may cease to exist when the invoked function returns.

    Regarding QML: The language has fairly strong rules regarding capitalization. Types should begin with an upper case letter. Properties and functions should begin with a lower case letter. Following the convention in C++ will make integration easier.



  • @LudoFR
    Don't worry about exact timings. Your 10 second timing indicates there are around 13,000 datagrams per second, which is just what you were originally expecting. Just make sure whatever processing you do on those datagrams is fast!



  • @jeremy_k said in QUdpSocket receive Datagram into QtConcurrent:

    Regarding QML: The language has fairly strong rules regarding capitalization. Types should begin with an upper case letter. Properties and functions should begin with a lower case letter. Following the convention in C++ will make integration easier.

    Agreed and thanks, but i need to make a choice for my compagny and our futur tools, C++, python, Qt, PyCharm, VS.. first I check the language, the possibilities, time to develop with, the compatibily with all the dependency we need...

    After our choice, I will check about the code convention, and use it in the final project, hope you have remarked this is not a real project !

    But it's clearly not my priority now....


Log in to reply