Search code examples
qtsocketsintegersendqtcpsocket

How to send integers over QTcpSocket?


I'm new to Qt, so if this is a completely stupid question...

I'm trying to use QTcpSocket.

If I do:

...
QTcpSocket * socket
socket = new QTcpSocket(this);
socket.write(1);
...

It complains about write() not working with integers (not a const char *).

If I do:

...
QTcpSocket * socket
socket = new QTcpSocket(this);
socket.write("1");
...

the other side sees it as the integer 49 (ASCII for 1).

On a similar but different issue, is it possible to send structs or unions over QTcpSocket?

==================================================

EDIT:

The server already accepts integers, and is expecting an integer - I have no control over that.


Solution

  • The problem you have is not really related to Qt, the same issue would arise with any other Socket or Streaming interface.

    The provider of the Server needs to give you the protocol description. This description usually contains the ports used (TCP, UDP, numbers), other TCP parameters and the coding of the transmitted data. Sometimes, this protocol (or its implementation) is called a (protocol-) stack.

    The coding not only contains the byte ordering, but also a description of how complex structures are transmitted. The latter information is often coded in something that is called "ASN.1" - Abstract Syntax Notation.

    In case your server is really simple and just accepts Integers one after the other without any meta-information and is on the same platform, than you could do something like this:

    foreach (int i in my set of integers)
    {
       ioDevice->write((const char*) &i, sizeof(i));
    }
    

    You take the address of your integer as a data buffer start and transmit as many bytes as your integer has. But note well, this will fail if you transmit data from an Intel architecture to a 16-bit architecture or a motorola PPC.