简体   繁体   中英

Python 2.7 TCP Sockets: socket.send() that returns zero versus socket.send() that raises socket.error exception?

From http://docs.python.org/2/howto/sockets.html

if a socket send or recv returns after handling 0 bytes, the connection has been broken.

On the other hand, if the remote end of the TCP connection closes (or is killed), and socket.send() is called subsequently, one can see the following socket.error exception

socket.error: [Errno 104] Connection reset by peer

Now my question is, what is the difference between " connection has been broken " and " Connection reset by peer ". And exactly what is meant by "connection has been broken" == socket.send() returns zero. To me, not being able to send even a single character is as bad as a socket.error exception. Whatever event that causes socket.send to return zero, should have ideally raised a socket.error exception, so that the application does not have to deal with two different things (exception and return value zero).

Getting RST is a very specific use-case in TCP protocol -- the peer sends a message back by setting the RST flag in the TCP header. It usually means that there is no socket endpoint at the peer. This scenario can happen if hte remote peer's machine rebooted suddenly without having a chance to close the socket gracefully (aka by using 4-way FIN messages). Once it comes back online, it has lost the earlier socket endpoint and if it recieves any new TCP packet for the older connection, then it will send a TCP message by setting the RST flag.

As opposed to receiving a RST, a connection could be closed due to other reasons. One of them them being a normal graceful of using the FIN messages. In such cases, the underlying connection at the TCP layer is closed. The other case could be that the the peer's connectivity was lost and there is a TCP Keepalive option set. For this case, when the peer becomes idle, TCP would send keepalive probes and since the connectivity is not there, there would be no replies to the Keepalive. Once the TCP layer does not receive a set of N keepalives, then it will close the connection locally. Calling Python's send and recv on such a socket returns 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM