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
' fun开发者_StackOverflow社区ction 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...
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).
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);
精彩评论