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
Forum Updated to NodeBB v4.3 + New Features

QTcpSocket not connecting

Scheduled Pinned Locked Moved Solved General and Desktop
13 Posts 5 Posters 2.7k Views 1 Watching
  • 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.
  • M Offline
    M Offline
    mzimmers
    wrote on 11 Oct 2018, 16:16 last edited by mzimmers 10 Nov 2018, 17:01
    #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.

    J 1 Reply Last reply 11 Oct 2018, 16:44
    0
    • M mzimmers
      11 Oct 2018, 16:16

      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.

      J Offline
      J Offline
      JonB
      wrote on 11 Oct 2018, 16:44 last edited by JonB 10 Nov 2018, 16:49
      #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.

      M 1 Reply Last reply 11 Oct 2018, 16:47
      1
      • J JonB
        11 Oct 2018, 16:44

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

        M Offline
        M Offline
        mzimmers
        wrote on 11 Oct 2018, 16:47 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).

        J A 2 Replies Last reply 11 Oct 2018, 16:51
        0
        • M mzimmers
          11 Oct 2018, 16:47

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

          J Offline
          J Offline
          JonB
          wrote on 11 Oct 2018, 16:51 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.

          A 1 Reply Last reply 11 Oct 2018, 16:58
          1
          • M Offline
            M Offline
            mzimmers
            wrote on 11 Oct 2018, 16:55 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
            • M mzimmers
              11 Oct 2018, 16:47

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

              A Offline
              A Offline
              aha_1980
              Lifetime Qt Champion
              wrote on 11 Oct 2018, 16:56 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.

              M 1 Reply Last reply 11 Oct 2018, 17:01
              4
              • J JonB
                11 Oct 2018, 16:51

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

                A Offline
                A Offline
                aha_1980
                Lifetime Qt Champion
                wrote on 11 Oct 2018, 16:58 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.

                J 1 Reply Last reply 11 Oct 2018, 17:45
                0
                • A aha_1980
                  11 Oct 2018, 16:56

                  @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

                  M Offline
                  M Offline
                  mzimmers
                  wrote on 11 Oct 2018, 17:01 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...

                  J 1 Reply Last reply 12 Oct 2018, 04:36
                  1
                  • M Offline
                    M Offline
                    MrShawn
                    wrote on 11 Oct 2018, 17:45 last edited by MrShawn 10 Nov 2018, 17:47
                    #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 :)

                    M 1 Reply Last reply 11 Oct 2018, 17:54
                    0
                    • A aha_1980
                      11 Oct 2018, 16:58

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

                      You shoud rather recommend to use the normal event loop.

                      J Offline
                      J Offline
                      JonB
                      wrote on 11 Oct 2018, 17:45 last edited by JonB 10 Nov 2018, 18:07
                      #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.

                      A 1 Reply Last reply 11 Oct 2018, 18:11
                      0
                      • M MrShawn
                        11 Oct 2018, 17:45

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

                        M Offline
                        M Offline
                        mzimmers
                        wrote on 11 Oct 2018, 17:54 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
                        • J JonB
                          11 Oct 2018, 17:45

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

                          A Offline
                          A Offline
                          aha_1980
                          Lifetime Qt Champion
                          wrote on 11 Oct 2018, 18:11 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
                          • M mzimmers
                            11 Oct 2018, 17:01

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

                            J Online
                            J Online
                            jsulm
                            Lifetime Qt Champion
                            wrote on 12 Oct 2018, 04:36 last edited by jsulm 10 Dec 2018, 04:37
                            #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

                            10/13

                            11 Oct 2018, 17:45

                            • Login

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