开发者

Perl : Set read timeout in client socket

I have created tcp client socket , after creating socket the connection got established with server . Then I am reading the content from server . In this case. I need to wait only for 10 seconds in read .开发者_StackOverflow If the nothing is read . It has to return in specified timeout. what is the way...?

Thanks


Assuming you are using the standard IO::Socket module (though there are older ways), you call the timeout method to set your timeout to 10 before reading.


perldoc -f alarm

If you want to use alarm to time out a system call you need to use an eval/die pair. You can't rely on the alarm causing the system call to fail with $! set to EINTR because Perl sets up signal handlers to restart system calls on some systems. Using eval/die always works, modulo the caveats given in Signals in perlipc.

eval {
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
    alarm $timeout;
    $nread = sysread SOCKET, $buffer, $size;
    alarm 0;
};
if ($@) {
    die unless $@ eq "alarm\n";   # propagate unexpected errors
    # timed out
}
else {
    # didn't
}

For more information see perlipc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜