June 21st, 2004, 11:31 PM
detecting closed sockets
I am writing a multi-threaded socket server in python 2.3.3 on a 3.0GHz p4 with 512MB of RAM.
I've got everything working flawlessly, but am unable to detect a disconnected socket. I have perused the docs and have been unabled to determine if there is a way to detect if a socket is in a disconnected or TIME_WAIT state. If I could even detect the TIME_WAIT, I could time the sockets and close them based on a predetermined timeout.
I've tried detecting the EOF on a socket or a send of 0 bytes, but that only works on those sockets that actually follow the standard. If you had a connection created by a simple client, such as nc for example, then the disconnects won't be caught.
Anyway, I'd appreciate any ideas that you all have to offer.
June 22nd, 2004, 01:09 AM
recv() will return 0 when a peer closes it's socket.
data = conn.recv(1024)
if not data: break
June 22nd, 2004, 09:29 AM
Is that on a non-blocking socket, a blocking socket or both?
Will it return 0 if you are trying to read from the socket as a stream?
e.g. Will this work?
fin = sock.makefile()
data = fin.readline()
if not data:
June 22nd, 2004, 09:33 AM
Also, if this is the case, then how does the socket differentiate between a socket who has had no activity and one who is actually no longer connected?
June 22nd, 2004, 10:16 AM
It will work on both a non-blocking and a blocking socket. If there is nothing to read on a blocking socket, it with block until there is something to read or the peer closes it's socket (return of 0). If the socket is non-blocking and there is nothing to read it returns and raises an exception with errno set as EWOULDBLOCK. If there is something to read, it's read and if the peer closes it's socket, like above, there is a return of 0.
As for the stream question, I don't know. Perhaps a little test will reveal the answer.
June 22nd, 2004, 01:04 PM
Ahh, fantastic. I will give it a whirl.
June 22nd, 2004, 02:30 PM
little example.. of when the remote host gets disconnected
hade it laying around.. decided to post it
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.bind(( '', 7777 ))
s.listen( 5 )
remote, addr = s.accept( )
if not remote.recv( 1025 ):
print 'Remote host disconnected'
June 22nd, 2004, 07:17 PM
just a note
After some additional testing, it appears that on some socket disconnects, there is no return of 0.
In the case of using nc (google netcat), there is no return of 0 when the client disconnects. You have to actually initiate a send of 0 bytes.
However, if you are using the socket in stream mode, and the socket does close properly, you will get the return of 0 bytes.
So, back to the drawing board.
June 22nd, 2004, 10:21 PM
The return of 0 isn't returned on the socket of the side that disconnected, it's on the peer side.
June 24th, 2004, 05:44 PM