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?
Asked
Active
Viewed 643 times
0

Community
- 1
- 1

michaeluskov
- 1,729
- 7
- 27
- 53
-
How are you using sockets on Windows? – squiguy Feb 26 '14 at 18:39
-
The `timeout` option is about establishing a socket connection, not reading data from a connection that is already established. – mob Feb 26 '14 at 18:44
1 Answers
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