When programming with sockets in Python, it is found that the client's TCP is often in the close_wait state: using commands in Linux
# NETSTAT-ATPN
The reason is that the server side shuts down the TCP connection, sends the FIN signal to the client, the client's TCP layer returns an ACK, and its socket state is in the close_wait state.
Experiment:
Python, the socket is in the close_wait state before send, then the send does not error, and after the execution of the socket is closed. Continue to call send will be an error.
Reasoning:
This shows that Python's socket.send checks the state of the socket before sending the data, and if it is in Close_wait, execute close (socket) (the application layer does not feel it) and then exit normally. So when send again, an exception is thrown.
Why is the close_wait state always in place.
When the socket is close_wait, the close (socket) must be called by the application tier to send the fin to the server to be last_ack and receive the ACK of the server-side response before it becomes closed. If the application layer does not call close (), the socket will always be close_wait. [1]
If I'm looping through Python to invoke Socket.sendall (), then when the socket becomes close_wait, the socket is closed through socket.sendall (), why is it still in the close_wait state?
The reason is that when sendall (data) has a large data ratio, the connection is broken by the server side when the data is sent in half. Then Sendall (data) will always be stuck there, will not be executed to the beginning of the Sendall, to determine the socket state, determine whether to close the socket.
Simply put, the socket is not called sendall () to close the socket after it becomes close_wait.
Reference documents:
[1] Explaining Close_wait-jane Lewis ' s weblog-site home-technet Blogs
[2] The reason and solution of the close_wait state of Linux socket communication-fly123456789-chinaunix Blog