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. Using QTcpSocket can I write a Tcp message with zero payload to server ?
Forum Updated to NodeBB v4.3 + New Features

Using QTcpSocket can I write a Tcp message with zero payload to server ?

Scheduled Pinned Locked Moved Solved General and Desktop
14 Posts 4 Posters 1.3k 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.
  • VRoninV Offline
    VRoninV Offline
    VRonin
    wrote on last edited by VRonin
    #2

    EDIT: solution below doesn't work

    Hi I can't test it right now but I seam to remember the correct way to do this is trying to read.
    Instead of writing a 0 payload packet, try reading from it:

    socket->startTransaction();
    socket->read(1);
    socket->rollbackTransaction();
    

    This code does nothing per se but it should trigger the detection that the server is now disconnected and emit the disconnected() signal

    "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
    ~Napoleon Bonaparte

    On a crusade to banish setIndexWidget() from the holy land of Qt

    KroMignonK 1 Reply Last reply
    2
    • VRoninV VRonin

      EDIT: solution below doesn't work

      Hi I can't test it right now but I seam to remember the correct way to do this is trying to read.
      Instead of writing a 0 payload packet, try reading from it:

      socket->startTransaction();
      socket->read(1);
      socket->rollbackTransaction();
      

      This code does nothing per se but it should trigger the detection that the server is now disconnected and emit the disconnected() signal

      KroMignonK Offline
      KroMignonK Offline
      KroMignon
      wrote on last edited by
      #3

      @VRonin said in Using QTcpSocket can I write a Tcp message with zero payload to server ?:

      Instead of writing a 0 payload packet, try reading from it:
      socket->startTransaction();
      socket->read(1);
      socket->rollbackTransaction();

      This code does nothing per se but it should trigger the detection that the server is now disconnected and emit the disconnected() signal

      Very cool workaround!
      I have no need of this now, but how knows, maybe in future development :)

      It is an old maxim of mine that when you have excluded the impossible, whatever remains, however improbable, must be the truth. (Sherlock Holmes)

      1 Reply Last reply
      0
      • S Offline
        S Offline
        sasanka
        wrote on last edited by
        #4

        Hi @VRonin i tried using your method, but still do not get any disconnected() signal emitted.
        Also tried setSocketOption with keepAlive parameter and performed read operation but no detection happens.
        So looking for other methods.

        KroMignonK 1 Reply Last reply
        0
        • VRoninV Offline
          VRoninV Offline
          VRonin
          wrote on last edited by
          #5

          Do you have access to the source of the server? Can you send a sort of heartbeat between the two?

          "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
          ~Napoleon Bonaparte

          On a crusade to banish setIndexWidget() from the holy land of Qt

          1 Reply Last reply
          0
          • S Offline
            S Offline
            sasanka
            wrote on last edited by
            #6

            Unfortunately no, i do not have access to change the server side code. So implementing heartbeat is difficult.

            1 Reply Last reply
            0
            • S sasanka

              Hi @VRonin i tried using your method, but still do not get any disconnected() signal emitted.
              Also tried setSocketOption with keepAlive parameter and performed read operation but no detection happens.
              So looking for other methods.

              KroMignonK Offline
              KroMignonK Offline
              KroMignon
              wrote on last edited by
              #7

              @sasanka said in Using QTcpSocket can I write a Tcp message with zero payload to server ?:

              Also tried setSocketOption with keepAlive

              I am using socket.setSocketOption(QAbstractSocket::KeepAliveOption, 1);, which works fine for me, but there are some things you have to known:

              • it must be done when socket is connected
              • the probe interval is per default at 12 hours! (or even more, I don't really remember)

              The easiest way I found to use it, was to enabled it "by hand", after my socket was connected:

              • on Linux systems:
                      int enableKeepAlive = 1;
                      int fd = socket->socketDescriptor();
                      setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &enableKeepAlive, sizeof(enableKeepAlive));
              
                      // Interval between the last data packet sent and the first keepalive probe in seconds.
                      int maxIdle = 15;
                      setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &maxIdle, sizeof(maxIdle));
              
                      // Number of probes that are sent and unacknowledged before the client considers
                      //the connection broken and notifies the application layer.
                      int count = 6;
                      setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &count, sizeof(count));
              
                      // Interval between subsequent keepalive probes in seconds.
                      int interval = 5;
                      setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &interval, sizeof(interval));
              
              • for Windows:
              #include <winsock2.h>
              #include <mstcpip.h>
              #include <Ws2tcpip.h>
              #pragma comment(lib, "ws2_32.lib")
              ...
                      int fd = socket->socketDescriptor();
                      DWORD dwBytesRet = 0;
                      tcp_keepalive alive;    // your options for "keepalive" mode
              
                      if(WSAIoctl(fd, SIO_KEEPALIVE_VALS, NULL, 0, &alive, sizeof(alive), &dwBytesRet, NULL, NULL) == SOCKET_ERROR) {
                          qWarning() << "WSAIotcl(SIO_KEEPALIVE_VALS) read failed with err#" <<  WSAGetLastError();
                          return;
                      }
                      qDebug() << qPrintable(QString("OnOff:%1, KeepAliveTime=%2, KeepAliveInterval=%3")
                                                 .arg(alive.onoff).arg(alive.keepalivetime).arg(alive.keepaliveinterval));
                      alive.onoff = TRUE;              // turn it on
                      alive.keepalivetime = 15000;     // delay (ms) between requests, default is 2h (7200000)
                      alive.keepaliveinterval = 5000;  // delay between "emergency" ping requests, their number (6) is not configurable
              
                      /*
                       * So with this config  socket will send keepalive requests every 15
                       * seconds after last data transaction when everything is ok.
                       *
                       * If there is no reply (wire plugged out) it'll send 6 requests with 5s
                       * delay between them and then close.
                       *
                       * As a result we will get disconnect after approximately 45 sec timeout.
                       */
                      if (WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), NULL, 0, &dwBytesRet, NULL, NULL) == SOCKET_ERROR) {
                          qWarning() << "WSAIotcl(SIO_KEEPALIVE_VALS) write failed with err#" <<  WSAGetLastError();
                          return;
                      }
              

              It is an old maxim of mine that when you have excluded the impossible, whatever remains, however improbable, must be the truth. (Sherlock Holmes)

              1 Reply Last reply
              4
              • S Offline
                S Offline
                sasanka
                wrote on last edited by
                #8

                I had to include LIBS += -lws2_32 in the .pro file while using the above code.
                After segregating and adding the above code to my project i get the following Warning/Error at runtime. May be the socket is unable to initialize properly with the WSAIoctl . The message is as follows.

                WSAIotcl(SIO_KEEPALIVE_VALS) read failed with err# 10093

                JonBJ KroMignonK 2 Replies Last reply
                0
                • S sasanka

                  I had to include LIBS += -lws2_32 in the .pro file while using the above code.
                  After segregating and adding the above code to my project i get the following Warning/Error at runtime. May be the socket is unable to initialize properly with the WSAIoctl . The message is as follows.

                  WSAIotcl(SIO_KEEPALIVE_VALS) read failed with err# 10093

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

                  @sasanka said in Using QTcpSocket can I write a Tcp message with zero payload to server ?:

                  read failed with err# 10093

                  What have you done about calling WSAStartup()?

                  1 Reply Last reply
                  0
                  • S sasanka

                    I had to include LIBS += -lws2_32 in the .pro file while using the above code.
                    After segregating and adding the above code to my project i get the following Warning/Error at runtime. May be the socket is unable to initialize properly with the WSAIoctl . The message is as follows.

                    WSAIotcl(SIO_KEEPALIVE_VALS) read failed with err# 10093

                    KroMignonK Offline
                    KroMignonK Offline
                    KroMignon
                    wrote on last edited by KroMignon
                    #10

                    @sasanka said in Using QTcpSocket can I write a Tcp message with zero payload to server ?:

                    WSAIotcl(SIO_KEEPALIVE_VALS) read failed with err# 10093

                    According Microsoft documentation (https://docs.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2), this is WSANOTINITIALISED:

                    Successful WSAStartup not yet performed.

                    Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.

                    When did you try to set KeepAlive?
                    Was your socket in connected state (socket->state() == QAbstractSocket::ConnectedState)?

                    It is an old maxim of mine that when you have excluded the impossible, whatever remains, however improbable, must be the truth. (Sherlock Holmes)

                    1 Reply Last reply
                    1
                    • S Offline
                      S Offline
                      sasanka
                      wrote on last edited by
                      #11

                      Hi @JonB Yes I checked through the error codes from Microsoft website and added the WSAStartup() with parameters as provided in their documentation.

                      Hi @KroMignon i made sure to invoke KeepAlive with the above mentioned code once the client has connected with the server.
                      It now gives the following error message from WSAIotcl.

                      WSAIotcl(SIO_KEEPALIVE_VALS) read failed with err# 10014

                      From the error codes listed in MS Documentation.
                      WSAEFAULT
                      10014
                      Bad address.
                      The system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small. For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).

                      Maybe the function the parameters have discrepancies
                      WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), NULL, 0, &dwBytesRet, NULL, NULL)

                      KroMignonK 1 Reply Last reply
                      0
                      • S Offline
                        S Offline
                        sasanka
                        wrote on last edited by
                        #12

                        @sasanka said in Using QTcpSocket can I write a Tcp message with zero payload to server ?:

                        WSAIoctl

                        sry below is the function with read failed.
                        WSAIoctl(fd, SIO_KEEPALIVE_VALS, NULL, 0, &alive, sizeof(alive), &dwBytesRet, NULL, NULL)

                        1 Reply Last reply
                        0
                        • S sasanka

                          Hi @JonB Yes I checked through the error codes from Microsoft website and added the WSAStartup() with parameters as provided in their documentation.

                          Hi @KroMignon i made sure to invoke KeepAlive with the above mentioned code once the client has connected with the server.
                          It now gives the following error message from WSAIotcl.

                          WSAIotcl(SIO_KEEPALIVE_VALS) read failed with err# 10014

                          From the error codes listed in MS Documentation.
                          WSAEFAULT
                          10014
                          Bad address.
                          The system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small. For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).

                          Maybe the function the parameters have discrepancies
                          WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), NULL, 0, &dwBytesRet, NULL, NULL)

                          KroMignonK Offline
                          KroMignonK Offline
                          KroMignon
                          wrote on last edited by
                          #13

                          @sasanka said in Using QTcpSocket can I write a Tcp message with zero payload to server ?:

                          Hi @KroMignon i made sure to invoke KeepAlive with the above mentioned code once the client has connected with the server.
                          It now gives the following error message from WSAIotcl.
                          WSAIotcl(SIO_KEEPALIVE_VALS) read failed with err# 10014

                          I use this code on WindowsXP/Windows7 devices, and it works fine;

                              connect(socket, &QTcpSocket::stateChanged, socket, [this]()
                                      {
                                          if(!socket)
                                              return;
                                          if(socket->state() == QAbstractSocket::ConnectedState)
                                              enableKeepAlive(socket);
                                      } );
                          

                          Which OS are you targeting?

                          It is an old maxim of mine that when you have excluded the impossible, whatever remains, however improbable, must be the truth. (Sherlock Holmes)

                          1 Reply Last reply
                          0
                          • S Offline
                            S Offline
                            sasanka
                            wrote on last edited by
                            #14

                            Hi @KroMignon I am using Windows 10 operating system.
                            I changed the parameters from WSAIoctl after reading the documentation.
                            Upon using the following function after setting alive parameters i am able to receive disconnect signal.

                            WSAIoctl(fd, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), NULL, 0, &dwBytesRet, NULL, NULL)

                            I tried powering off the server machine and my client application detects the state. In addition I changed the parameters for alive to detect the disconnect little early.

                            alive.onoff = TRUE; // turn it on
                            alive.keepalivetime = 600; // delay (ms) between requests, default is 2h (7200000)
                            alive.keepaliveinterval = 600; // delay between "emergency" ping requests, their number (6) is not configurable

                            Thanks a lot finally it works !!!

                            1 Reply Last reply
                            1

                            • Login

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