How to tell when a socket is closed on the other end?
python at jayloden.com
Thu Jul 26 09:53:25 CEST 2007
Roy Smith wrote:
> In article <1185371863.622473.205010 at 19g2000hsx.googlegroups.com>,
> billiejoex <gnewsg at gmail.com> wrote:
>> Hi there.
>> I'm setting up test suite for a project of mine.
>> >From test suite, acting as a client, I'd like to know, in certain
>> situations, if the socket is closed on the other end or not.
>> I noticed that I can "detect" such state if a call to socket.read()
>> returns 0 but it seems a little poor to me. :-\
>> Is there a reliable way to test such socket 'state'?
> This isn't really a Python question, it's a Berkeley Socket API question.
> You don't say, but I assume you're talking about a TCP (i.e. SOCKSTREAM)
> The answer is you can use the select() system call to detect "exceptional
> conditions" on a socket. Python's select module provides this
> functionality, but to understand how to use it, you need to study the
> underlying API.
Thanks for the interesting information and suggestion of using select(). You are correct that this is actually mostly a socket API question but pertains to Python since the code is all Python's socket and asyncore modules. It might help to step back and explain the original problem. The goal of this portion of the test suite we are writing for the project is to determine if a remote server is behaving properly by closing a socket from the server side based on a client-side command.
Really what's needed is a way to make sure the socket gets closed, and preferably determine if it was closed from the remote end as expected. Do you know if this is possible to determine from the client side reliably/accurately? Would select()'s exceptional condition flag actually indicate whether or not the root cause of the condition was a socket closed by the remote peer? I've read through the select's manpage and I can't seem to find a reference that indicates what the possible values are for the I/O descriptor sets returned by select. Is there another man page, or a place in the header file for select I can look?
Thanks for your help,
More information about the Python-list