Background:
At work, I write a TCP tool in Python, and then use the while loop to receive messages and print them. Then normal close found that the device is not offline, and then use a temporary evasion scheme, found that in fact, has been blocked in the recv () Receive method, as long as the transmission of a protocol, let recv () eat the message can be normal operation while to let its break exit, but this avoidance method is temporary, Treatment to cure its root, so the current socket is studied.
Cause of the problem:
Although the connection has been close off, but the client side can still successfully receive the message, and if the client side to send the data interval is less than the timeout period, this connection can be used smoothly, so that close seems to have no effect, after Baidu search, has not found a solution, and finally to bite the bullet to see the birds, the following is the official explanation:
Close ()releases the resource associated with a connection but does not necessarily close the connection immediate Ly. If you want to close the connection with a timely fashion, callshutdown () beforeClose ().
The general meaning is: The Close method can release a connected resource, but is not immediately released, if you want to release immediately, then use the Shutdown method before close
Workaround :
Continue to watch the birds, the official explanation is as follows:
shut_rd , further receives Is disallowed. if how is SHUT_WR , further sends is Disallowed. If how is shut_rdwr , further sends and Receives is disallowed. Depending on the platform, shutting down one half of the connection can also close the opposite half (e.g. on Mac OS X,&NB Sp shutdown (SHUT_WR) does not allow further reads on the other end of the connection) .
The general meaning is: The Shutdown method is used to implement the communication mode, the mode is divided into three kinds, theSHUT_RD closes the receiving message channel,SHUT_WR closes the sending message channel,SHUT_RDWR two channels are closed.
In other words, if you want to close a connection, first turn off the channel, and the above three static variables correspond to the numeric constants: 0,1,2
In layman's words, add the shutdown (2) method in front of close () to
Python close () is an illusion, the way to really close the socket