Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does python socket library not include recvall() method like sendall()?

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?

like image 501
flymike Avatar asked Aug 04 '14 14:08

flymike


People also ask

What is sendall in socket Python?

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.

What is the use of socket Recvfrom () method in Python?

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.

Is Python Recvfrom blocking?

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.

How is Python socket different from file handle?

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.


2 Answers

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.

like image 130
NPE Avatar answered Sep 24 '22 19:09

NPE


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.

like image 41
chepner Avatar answered Sep 26 '22 19:09

chepner