Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Handling server socket error and reconnect

by thospel (Hermit)
on Nov 09, 2004 at 01:31 UTC ( [id://406256]=note: print w/replies, xml ) Need Help??


in reply to Handling server socket error and reconnect

Writing to a closed socket causes a SIGPIPE, which is a signal, not an exception. So you have to handle that somewhow, ignore is usually simplest. Then writing to a closed socket becomes just a normal I/O error. Assuming we don't have to worry about the speed at which I/O progresses, the code becomes:
#! /usr/bin/perl -w use strict; use IO::Socket::INET; $SIG{PIPE} = "IGNORE"; my $client; sub call_server { my $answer; for (0..1) { return $answer if $client and print $client "some_command\n" and defined($answer = <$client>); $client = IO::Socket::INET->new(PeerAddr => "localhost", PeerPort => 16666) or die "Couldn't connect to server: $!"; } die "Server in trouble"; } foreach(1..10) { print call_server(); sleep 10; # allow sometime to test server restart }
(warning, only minimally tested)

updated: code didn't take into account that a write might still get out, and only the read will notice the close. Also be more paranoid about a bad server, only retry once and assume an immediate second failure is a sign of server problems.

updated: make the looping on first call consistent too.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://406256]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2024-04-19 21:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found