Is socket.recv(1024) non-deterministic by design?

Viewed 37

My server uses a single

socket.recv(1024)

and my client sends a sequence of three messages. The total size of the three messages is smaller than 1024.

It seems the amount of messages received by the client in each reception is different for different runs. Sometimes the server one message; sometimes two or three.

Is socket.recv(1024) non-deterministic by design?

1 Answers

Is socket.recv(1024) non-deterministic by design?

It depends on what type of socket you are using.

If socket is of type SOCK_DGRAM, then recv() will return the contents of exactly one received (typically UDP) packet. Note that UDP packets can (and do) get dropped sometimes, so a sent packet might not get received at all, and packets might be received in a different order from the order in which they were sent. It is guaranteed, however, that you will receive either all of a packet, or none of it -- unless your supplied buffer-size is too short to hold all of the packet's data, in which case you'll only get as much data as your buffer can hold, and the remainder of the packet's data will be lost.

OTOH if socket is of type SOCK_STREAM, then recv() will return as many bytes of incoming data as it can currently give you, as determined by the network layer.

For TCP-based SOCK_STREAM sockets in particular, it's important to note that TCP guarantees that bytes will be received in the order they were sent, but it does not guarantee that they will be received in the same groupings that were originally passed to send(). So for example, if the sending program sends 1000 bytes via a single call to send(), the receiving program might receive all 1000 bytes via a single call to recv(), but it's just as likely that it might receive 500 bytes and then another 500 bytes on the next call, or 25 bytes and then 75 bytes and then 900 bytes, or even (in principle, at least) 1000 separate single-byte deliveries, or any other combination you can imagine. The TCP layer reserves the right to repackage the byte-boundaries however it sees fit, based on network conditions. If that is the indeterminacy you are asking about, then yes, it is by design, and your receiving program needs to be smart enough to handle the data appropriately regardless.

Related