In all examples of using bsd sockets on C, an array of characters of a fixed length char buff[255] used to transmit and receive information char buff[255] . For example, read(socketFD, buff, sizeof(buff)); . A couple of questions arise:

  1. Is it necessary to use an array of char, or can I pass arbitrary objects? for example, is it possible to pass double buff[255] or even struct someStructType buff[255] ?

  2. What happens if you send an array of, for example, 200 elements, and on the receiving side only 100 are counted? When re-reading, we read the same elements, or the next 100 elements?

  • Bytes are transmitted and nothing but bytes. How you will translate "any type" into bytes and vice versa is up to you. If you can translate, you can transfer. - Vladimir Martyanov
  • one
    2) What will happen if you pour 100 out of a 200-liter barrel, close the tap and open it again? - PinkTux

2 answers 2

Only bytes are transferred to the socket in order to convert your objects into bytes or to create them from them you need to use serialization protocols such as TLV or ProtoBuf.
The examples provide an array buffer for reading information into it; as a rule, the read function returns the actual number of bytes read. If you send 200 bytes, and consider 100, then you will need to read another 100 later.
The buffer can be of any size (but as a rule it is made no more than MTU / MRU). As a rule, when communicating over the network, they are packaged in a packet of the form: packetLength:packetData , which allows you to read the transmitted packet guaranteed. So, for example, sending 200 bytes of the necessary information you:

  1. Read the data from the socket into the receive buffer.
  2. Read from this buffer the packetLenght packet packetLenght (how many bytes - depends on the type of variable and architektru);
  3. Create a buffer of size packetLength . This is not the same buffer you are reading from the socket !!
  4. Copy from the receive buffer the data in the created buffer, while if the data size is less than what is left in the buffer, then you need to copy the number, if more, write everything and then read from the socket to the receive buffer until pull out all.

    The first, in essence, is the issue of portability. You simply pass a block of bytes. We need guarantees of their correct interpretation from the other side. Suddenly there is a different byte order? Other data format? Or something else? That's why the most generalized version is used - just some bytes. As for the structures, consider alignment as well. I hope what is fraught with the transfer of just objects in the spirit

     string s; write(fd, &s, sizeof(s)); 

    you understand? :) And some people manage ...

    The second is to read the next 100 bytes when reading next. Unless, of course, before you close the connection :)