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. QTcpSocket not connecting
QtWS25 Last Chance

QTcpSocket not connecting

Scheduled Pinned Locked Moved Solved General and Desktop
13 Posts 5 Posters 2.7k 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.
  • mzimmersM Offline
    mzimmersM Offline
    mzimmers
    wrote on last edited by mzimmers
    #1

    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.

    JonBJ 1 Reply Last reply
    0
    • mzimmersM mzimmers

      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.

      JonBJ Offline
      JonBJ Offline
      JonB
      wrote on last edited by JonB
      #2

      @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.

      mzimmersM 1 Reply Last reply
      1
      • JonBJ JonB

        @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.

        mzimmersM Offline
        mzimmersM Offline
        mzimmers
        wrote on last edited by
        #3

        @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).

        JonBJ aha_1980A 2 Replies Last reply
        0
        • mzimmersM mzimmers

          @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).

          JonBJ Offline
          JonBJ Offline
          JonB
          wrote on last edited by
          #4

          @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.

          aha_1980A 1 Reply Last reply
          1
          • mzimmersM Offline
            mzimmersM Offline
            mzimmers
            wrote on last edited by
            #5

            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())?

            1 Reply Last reply
            0
            • mzimmersM mzimmers

              @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).

              aha_1980A Offline
              aha_1980A Offline
              aha_1980
              Lifetime Qt Champion
              wrote on last edited by
              #6

              @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

              Qt has to stay free or it will die.

              mzimmersM 1 Reply Last reply
              4
              • JonBJ JonB

                @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.

                aha_1980A Offline
                aha_1980A Offline
                aha_1980
                Lifetime Qt Champion
                wrote on last edited by
                #7

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

                You shoud rather recommend to use the normal event loop.

                Qt has to stay free or it will die.

                JonBJ 1 Reply Last reply
                0
                • aha_1980A aha_1980

                  @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

                  mzimmersM Offline
                  mzimmersM Offline
                  mzimmers
                  wrote on last edited by
                  #8

                  @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...

                  jsulmJ 1 Reply Last reply
                  1
                  • M Offline
                    M Offline
                    MrShawn
                    wrote on last edited by MrShawn
                    #9

                    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 :)

                    mzimmersM 1 Reply Last reply
                    0
                    • aha_1980A aha_1980

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

                      You shoud rather recommend to use the normal event loop.

                      JonBJ Offline
                      JonBJ Offline
                      JonB
                      wrote on last edited by JonB
                      #10

                      @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.

                      aha_1980A 1 Reply Last reply
                      0
                      • M MrShawn

                        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 :)

                        mzimmersM Offline
                        mzimmersM Offline
                        mzimmers
                        wrote on last edited by
                        #11

                        @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.

                        1 Reply Last reply
                        0
                        • JonBJ JonB

                          @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.

                          aha_1980A Offline
                          aha_1980A Offline
                          aha_1980
                          Lifetime Qt Champion
                          wrote on last edited by
                          #12

                          @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

                          Qt has to stay free or it will die.

                          1 Reply Last reply
                          4
                          • mzimmersM mzimmers

                            @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...

                            jsulmJ Offline
                            jsulmJ Offline
                            jsulm
                            Lifetime Qt Champion
                            wrote on last edited by jsulm
                            #13

                            @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.

                            https://forum.qt.io/topic/113070/qt-code-of-conduct

                            1 Reply Last reply
                            0

                            • Login

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