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

I am very new to perl and I am trying to write some code that is portable accross OS's and part of the code is making socket calls to a remote server. However I need the sockets to timeout when the response takes too long. Even with the timeout value set when I create the socket, the script does not timeout and continues to wait until it recieves a response on the socket or the webserver kills the script because it is taking too long to execute. What am I doing wrong, and can I explicitly check to see if a timeout occured? The socket communciations are working apart from the timeout issue. I have extracted the sockets code that I am using. Any feedback is welcome.
use strict; use CGI; use IO::Socket; my $clientIP = $params{'HostName'}; my $clientPort = $params{'Port'}; my $client = undef; my $timeOut = 10; my $reqString = $params{'RequestString'}; my $resString = ""; $client = IO::Socket::INET->new ( PeerAddr => $clientIP, PeerPort => $clientPort, Proto => "tcp", Type => SOCK_STREAM, Timeout => $timeOut ); # Send the request (appended with a newline character) to the sock +et print $client $reqString."\n"; # Retrieve the response from the socket buffer $resString = <$client>;

Replies are listed 'Best First'.
Re: Implementing Sockets Timeouts
by DigitalKitty (Parson) on Aug 02, 2002 at 02:39 UTC
    Hi Anonymous Monk,

    Internally, IO::Socket uses non-blocking i/o with regard to timeouts. I would specify an integer for the timeout period since I didn't see where it was passed in via a form. Something like this:

    #!/usr/bin/perl -wT use strict; use CGI qw( :standard ); use IO::Socket; my $client = IO::Socket::INET->new ( PeerAddr => $clientIP, PeerPort => $clientPort, Proto => "tcp", Type => SOCK_STREAM, Timeout => 10 ); $client or die $@, "\n"; #Remainder of code...

    If the connection occurs within the alloted time frame, the IO::Socket obj. is returned and saved in $client. If not, the error will be stored in $@ with the error message "IO::Socket::INET:Operation now in progress".
    Hope this helps,
    -Katie.
      Hi Katie,

      Thanks for your help. Your suggestion on the error message contained in $@ solved my problem.

      Chris