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

QTcpSocket not connecting



  • Hi all -

    Code passage:

    void Worker::updateFirmware(string targetIp)
    {
        QTcpSocket *sock;
        QString ip;
        QAbstractSocket::SocketState state;
    
        sock = new QTcpSocket;
        ip = QString::fromStdString(targetIp);
        sock->connectToHost(ip, OTA_PORT_NBR);
        while ((state = sock->state()) != QAbstractSocket::ConnectedState)
        {
            qDebug() << "socket state " << state << endl;
        }
        delete sock;
    }
    

    (This is for debugging purposes only.)

    According to Wireshark, I should be connected:
    0_1539274510808_wireshark.PNG
    But state() keeps returning ConnectingState. What am I doing wrong?

    Thanks...

    EDIT:

    I just added this below my connectToHost() call:

        if (sock->waitForConnected(-1))
        {
            qDebug("Connected!");
        }
    

    And...now it works. Odd...if anyone can explain this behavior to me, I'd appreciate it.



  • @mzimmers
    I suspect because sock->waitForConnected(-1) gives your socket a moment to breathe!

    When you wrote:

        while ((state = sock->state()) != QAbstractSocket::ConnectedState)
        {
            qDebug() << "socket state " << state << endl;
        }
    

    unless sock->state() allows whatever to run in the socket code (which I doubt, it probably just fetches a variable's value?) this looks like a busy loop? It never gets given a chance to progress on from "connecting" to "connected"?

    P.S.
    I don't want to get into a debate about your architecture, threads etc., but with Qt and signals/slots you don't want to be writing "busy/waiting loops" like checking sock->state() in a while; you want to architect off signals & slots always.



  • @JonB yeah, the code is totally unusable outside the debugger; I was just stepping through it to try to figure out what's going on. I did have a small delay in there with the same results. Still seems to me that it should work without the waitForConnected() call (which returns virtually instantly, BTW).



  • @mzimmers

    I did have a small delay in there with the same results

    And what exactly was the code for that delay? More loop code? A sleep function? I would guess something like that? They won't hack it. Did you try calling QCoreApplication::processEvents() in your "delay"?

    P.S.
    I added a P.S. to my previous post.



  • Yes, the delay was a sleep. So, do I understand that the preferred method for this would be to call connectToHost() and then wait for a "connected" signal (or call waitForConnected())?


  • Lifetime Qt Champion

    @mzimmers

    QTcpSocket, like most asynchronous Qt objects, need the event loop to do it's work.

    There are several signals available to do this async programming, e.g. connected.

    See e.g. [this example}(http://doc.qt.io/qt-5/qtnetwork-fortuneclient-example.html)

    The waitFor... functions should only be used in threads outside the main thread.

    Regards


  • Lifetime Qt Champion

    @JonB I'm about to downvote your post recommending processEvents().

    You shoud rather recommend to use the normal event loop.



  • @aha_1980 as it turns out, this is a worker thread (therefore outside the main thread), so I guess it's OK this time, but I'll keep your warning in mind. Thanks...



  • Maybe waitForConnected() instead of your while loop?

    myConnection.connectToHost(mySettings.getServerAddress(),mySettings.getServerPort());
    
    if (!myConnection.waitForConnected())
        throw QString("Unable to Connect: " + myConnection.errorString());
    

    Are you able to open a connection via telnet or something of the like?

    **EDIT
    Did not see he got it working already, it was unsolved :)



  • @aha_1980

    I'm about to downvote your post recommending processEvents().

    That would be cruel! :) I did not "recommend" processEvents().

    The OP asked a question: how come waitForConnected(-1) did allow his code to work, when he had instead put in a delay and that did not? I merely pointed out that if he put in a delay like a "sleep" with no processEvents() it would not allow the socket state to change. (I recommended he does not use "wait"s.)

    Let's put it this way: how would you explain to someone that sock->waitForConnected(-1) does work? I agree entirely with your

    QTcpSocket, like most asynchronous Qt objects, need the event loop to do it's work.

    and was trying to show therefore while a busy loop/sleep would not resolve his issue.



  • @MrShawn thanks. I haven’t marked it solved yet because people are still providing information that contributes to my knowledge base. Will mark it soon.


  • Lifetime Qt Champion

    @JonB said in QTcpSocket not connecting:

    That would be cruel! :) I did not "recommend" processEvents().

    You see, I'm not so cruel :) Well, everybody reading this might think it is a good idea.

    When searching for an example I found a bad one, using waitForConnected() in the main thread. That is horrible. People will start working that way, and maybe it works, but it's surely not designed that way.

    Let's put it this way: how would you explain to someone that sock->waitForConnected(-1) does work? What is in its code?

    I could look that up, but let's rather treat it as black box - the implementation might change anytime. What stays are three points:

    • only use it in threads outside the main (GUI) thread
    • don't use it in combination with signals&slots
    • after the call, you are either connected (returned true) or an error occurred (returned false).

    Regards


  • Lifetime Qt Champion

    @mzimmers said in QTcpSocket not connecting:

    so I guess it's OK this time

    No, it's not as your worker thread has its own event loop and your while(...) loops blocks it. With Qt and any other event driven framework there is one simple but fundamental rule: don't block the event loop.


Log in to reply