I already saw code to receive data through sockets which contains two loops:
...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.
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:
all of the messages are a fixed-length. The receiver simply reads that many bytes each time.
the sender sends a message's length before sending the message itself. The receiver reads the length first, then reads however many bytes the length says.
the sender sends a unique terminator after each message. The receiver reads until that terminator is 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.