Ezra
Ezra

Reputation: 1481

what does it mean when python socket.sendall returns successfully?

In my code I wrote something like this:

try:
    s.sendall(data)
except Exception as e:
    print e

Now, can I assume that if there wasn't any exception thrown by sendall that the other side of the socket (its kernel) did receive 'data'? If not then that means I need to send an application ack which seems unreasonable to me.

If I can assume that the other side's kernel did receive 'data' then that means that 'sendall' returns only when it sees tcp ack for all the bytes I have put in 'data' but I couldn't see any documentation for this, on the contrary, from searching the web I got the feeling that I cannot assume an ack was received.

Upvotes: 3

Views: 4388

Answers (2)

James Mills
James Mills

Reputation: 19050

Yes you can :)

According to the socket.sendall docs:

socket.sendall(string[, flags]) Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from string until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent.

Specifically:

socket.sendall() will continue to send all data until it has completed or an error has occurred.

Update: To answer your comment about what's going on under the hook:

Looking at the socketmodule.c source code it looks like it repeatedly tries to "send all data" until there is no more data left to send. You can see this on L3611 } while (len > 0);. Hopefully this answers your question.

Upvotes: 1

Steffen Ullrich
Steffen Ullrich

Reputation: 123380

can I assume that if there wasn't any exception thrown by sendall that the other side of the socket (its kernel) did receive 'data'?

No, you can't. All it tells you that the system successfully sent the data. It will not wait for the peer to ACK the data (i.e. data received at the OS kernel) or even wait until the data got processed by the peer application. This behavior is not specific to python.

And usually it does not matter much if the peer systems kernel received the data and put it into the applications socket buffer. All what really counts is if it received and processed the data inside the application, which might involve complex things like inserting the data into a database and waiting for a successful commit or even forwarding the data to yet another system. And since it is up to the application to decide when the data are really processed you have to make your application specific ACK to signal successful processing.

Upvotes: 3

Related Questions