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.
  • S Offline
    S Offline
    sasanka
    wrote on 24 Mar 2021, 10:31 last edited by
    #1

    Hello Everyone,

    I am trying to send a Tcp Packet whose payload is empty to a server. I already tried using the "write()" API's from QTcpSocket with length as zero but I do not observe the TcpPacket over wireshark.

    The reason I want to do that is
    I have a desktop client app running with QTcpSocket connected to server on Raspberry Pi. The server is sometimes powered off by unplugging and I want to detect its state in my Client App. Strangely in this situation the disconnect or stateChanged signals from QTcpSocket do not trigger. So the only way is to write a Tcp packet with payload zero periodically to server to trigger the signal disconnect. I do not want to fill the payload with even a single character as this causes faulty data sent to server.

    So is there a way around to send TCP packet with empty payload to server.

    Thanks in advance for suggestions.

    1 Reply Last reply
    0
    • V Offline
      V Offline
      VRonin
      wrote on 24 Mar 2021, 12:33 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

      K 1 Reply Last reply 24 Mar 2021, 13:49
      2
      • V VRonin
        24 Mar 2021, 12:33

        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

        K Offline
        K Offline
        KroMignon
        wrote on 24 Mar 2021, 13:49 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 24 Mar 2021, 15:07 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.

          K 1 Reply Last reply 24 Mar 2021, 16:06
          0
          • V Offline
            V Offline
            VRonin
            wrote on 24 Mar 2021, 15:58 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 24 Mar 2021, 16:01 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
                24 Mar 2021, 15:07

                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.

                K Offline
                K Offline
                KroMignon
                wrote on 24 Mar 2021, 16:06 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 25 Mar 2021, 09:25 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 K 2 Replies Last reply 25 Mar 2021, 09:45
                  0
                  • S sasanka
                    25 Mar 2021, 09:25

                    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 25 Mar 2021, 09:45 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
                      25 Mar 2021, 09:25

                      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

                      K Offline
                      K Offline
                      KroMignon
                      wrote on 25 Mar 2021, 09:46 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 25 Mar 2021, 10:19 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)

                        K 1 Reply Last reply 25 Mar 2021, 10:31
                        0
                        • S Offline
                          S Offline
                          sasanka
                          wrote on 25 Mar 2021, 10:23 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
                            25 Mar 2021, 10:19

                            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)

                            K Offline
                            K Offline
                            KroMignon
                            wrote on 25 Mar 2021, 10:31 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 25 Mar 2021, 10:48 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

                              1/14

                              24 Mar 2021, 10:31

                              • Login

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