When using recv() method, sometimes we can't receive as much data as we want, just like using send(). But we can use sendall() to solve the problem of sending data, how about receiving data? Why there is no such recvall() method?
sendall is a high-level Python-only method that sends the entire buffer you pass or throws an exception. It does that by calling socket. send until everything has been sent or an error occurs.
The recvfrom() method can be used with an UDP server to receive data from a UDP client or it can be used with an UDP client to receive data from a UDP server.
By default, Recvfrom() is blocking: when a process issues a Recvfrom() that cannot be completed immediately (because there is no packet), the process is put to sleep waiting for a packet to arrive at the socket.
A socket is much like a file, except that a single socket provides a two-way connection between two programs. You can both read from and write to the same socket. If you write something to a socket, it is sent to the application at the other end of the socket.
There is no fundamental reason why such a function could not be provided as part of the standard library. In fact, there has been at least one attempt to add recvall()
.
Given that it can be easily implemented as a loop around recv()
, I don't think that this is a major omission.
send
has extra information that recv
doesn't: how much data there is to send. If you have 100 bytes of data to send, sendall
can objectively determine if fewer than 100 bytes were sent by the first call to send
, and continually send data until all 100 bytes are sent.
When you try to read 1024 bytes, but only get 512 back, you have no way of knowing if that is because the other 512 bytes are delayed and you should try to read more, or if there were only 512 bytes to read in the first place. You can never say for a fact that there will be more data to read, rendering recvall
meaningless. The most you can do is decide how long you are willing to wait (timeout) and how many times you are willing to retry before giving up.
You might wonder why there is an apparent difference between reading from a file and reading from a socket. With a file, you have extra information from the file system about how much data is in the file, so you reliably distinguish between EOF and some other that may have prevented you from reading the available data. There is no such source of metadata for sockets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With