0

I need to make blocking socket read end by timeout. I read this question, I learned that IO::Socket::INET doesn't pay attention to Timeout option and learned about solution using eval/alarm. But I'm working on Windows and alarm doesn't work properly. Is there any other solution?

Community
  • 1
  • 1
michaeluskov
  • 1,729
  • 7
  • 27
  • 53

1 Answers1

1

Prior to reading from the socket, use the 4-argument version of select, with the desired timeout, to test whether any data is available on the socket to be read.

Also see the IO::Select module, and specifically the IO::Select::can_read($timeout) method to test if a socket read will block or not.

Example:

$read_timeout = 5.0; # seconds
$socket = IO::Socket->new( ... );     # socket to read from

$selector = IO::Select->new;
$selector->add( $socket );

...

@ready = $selector->can_read( $read_timeout );
if (@ready > 0) {
    $socket->read( $buffer, 128 );   # copy 128 bytes into $buffer
} else {
    warn "data not available on socket now";
}
mob
  • 117,087
  • 18
  • 149
  • 283