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

I'm using the following code to create client/server session.
my($client, $client_addr) = $server->accept();
I've noticed that if the client is abruptly disconneced that the server will crash when $client->send() is called. How can I be sure that the client is still valid before the $client->send() command is issued? Just checking that $client still exists isn't enough, it seems to exist long enough after a disconnect to cause problems.
#only send if $client exists $client->send() if $client;

Replies are listed 'Best First'.
Re: Client still valid?
by Zaxo (Archbishop) on Aug 04, 2003 at 23:58 UTC

    Are these IO::Socket objects? Assuming so, you can call $client->connected to check status. $client->send $msg, $opts if $client->connected(); Also, I think you should get SIGPIPE when the client disconnects, so a %SIG handler for that may be useful.

    After Compline,
    Zaxo

      perfect. Where can I find a complete listing of the options available on the $client object?

        The $client object is documented in 'perldoc IO::Socket'. It also inherits methods from IO::Handle.

        After Compline,
        Zaxo

Re: Client still valid?
by sgifford (Prior) on Aug 05, 2003 at 02:22 UTC

    In general, you can wrap the part of the program that's crashing in an eval block, then catch the errors instead of crashing:

    eval { $client->send() if $client; }; if ($@) { handle-error }

    Solutions that involve checking whether the client is still connected are better, but still involve race conditions. There are two seperate steps---checking if they're connected, then sending the data---and if the client disconnects between those two steps the check won't have done any good. It won't happen very often, but it can happen, and it will when the server has been used enough times in the Real World.

    Also, it's strange that a failed $client->send() would cause your script to crash instead of simply returning an error status. What error message does it exit with?

Re: Client still valid?
by adrianh (Chancellor) on Aug 04, 2003 at 23:54 UTC

    More info needed.

    What kind of thing are $server and $client? Is it from a CPAN module?

    Define "crash"?