scmason has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have a forking server that uses standard sockets ( use Socket ) and accepts new connections like:
my $client = accept( SESSION, SOCK );
When we accept a new session, we can read and write to the socket through the <SESSION> filehandle. Like so:
while( $newmessage = <SESSION> ){ #do something }
or
print SESSION "Here is your reply\n";
Everything works great, except I am not sure how to detect a dropped connection when working with the filehandle that I got from accept().

Once the client connects, the server starts processing some information and does not talk on the socket for a while. Sometimes the client decides they dont want to wait for results, so they disconnect. I would like to know when this happens so that I can stop processing the request. I dont mind checking it every couple of iterations, but I don't know the procedure.

I tried googling but nothing useful came back right away, so I am putting it in your hands!

Thanks

20050316 Edit by ysth: p and code tags

Replies are listed 'Best First'.
Re: Detecting Dead Socket Connection
by scmason (Monk) on Mar 17, 2005 at 00:09 UTC
    OK, I found the answer I think.

    if( eof(SESSION) == 1 ){ stopProcessing() }

    This seems to work.

      The problem here with eof() is that eof() reads a byte from the handle and then pushes it back on. The problem is that it can't read a byte until one is available (using ugetc()), so it blocks.
      There is a problm with my solution as I need to use it(thanks for the votes though). eof(SESSION) blocks until it IS EOF and then continues on its merry way. This does not work if you want to use this is a loop.

        I think what you want is to use select to see if there is anything ready to be read before calling eof. Well, I kinda lied. Using select is sorta like drilling a hole in one's head - you can do it, but you probably want another solution.

        That's where IO::Select comes in. Same piercing, but much faster (to figure out) and less painful. You can assign a timeout, and then do what you want with the filehandle. As long as the socket remains open and unused, select should timeout, but if the socket is closed, select should return the status change (probably by asking "has_exception", but I haven't tested this).