Manoj
Manoj

Reputation: 5087

Perl TCP read not timing out

I am trying to read data over TCP using the IO::Socket module. I read data either using the 'recv' function or <TCP_SOCKET> . Randomly, I find that the program hangs at that particular line where I am trying to read the data over TCP. The program does not proceed or exit unless I kill it. Why would this happen or how to avoid this from happening?

Thanks...

Upvotes: 0

Views: 913

Answers (2)

Francisco R
Francisco R

Reputation: 4048

I prefer to use IO::Socket::INET and i have had similar problems with timeouts. I solved it using an alarm.

use IO::Socket::INET;
my $socket = IO::Socket::INET->new(  PeerAddr => $HOST,
    PeerPort => $PORT,
    Proto    => 'tcp',
    Timeout  => 20,    # It seems to be ignored.
);


eval {
       local $SIG{ALRM} = sub { die "TimedOut" };
       alarm 20; # 20 seconds global timeout for receiving.

       $res = <$socket>;

       # your code here. 

       # Disable timeout alarm after receiving.
       alarm 0;
    }

    if ($@) {
       if ($@  eq "TimedOut") {
          print "Warning: timeout receiving\n";
       }
       else {
          print "Error receiving.";
       }
    }
    close ($socket);

Upvotes: 1

weismat
weismat

Reputation: 7411

You need to perform a

select

to determine if there is any data pending before the

recv

function to avoid a hang. Which platform are you talking about?

Have a look at select doc and IO::Socket doc.
In terms of other documents, I would recommend either "Network Programming with Perl" from Stein or the classical Stevens "Unix Network Programming".
Practically it is based to use a echo/ping protocol, because not all physical network problems trigger exceptions (e.g. when just unplugging a network cable on one machine, the remote machine does not see it).

Upvotes: 2

Related Questions