loopssocketsdelphisizedelphi-10.4-sydney

Why receive the length of data in a loop?


I already saw code to receive data through sockets which contains two loops:

  1. Receive length of data
  2. Receive data itself

...for example (see these answers):

...but the length of the data is not so big as the data itself. Then what's the goal of this "extra loop" to receive only a string like '1048'? I belive that could be received in one single loop together with the data itself.


Solution

  • TCP is a byte stream, it has no concept of messages. So, there are only 3 ways for the receiver to know when a full message has been received:

    There is no 1:1 relationship between a send and a read on a TCP socket. Any individual read operation can return fewer bytes than requested, so you need a loop to make sure you have received all of the bytes that you are expecting.

    So, in the 2nd case, one loop is needed for reading the bytes of the message length, and then another loop for reading the bytes of the message.