use IO::Select;
my $sock_read_hdl = IO::Select->new();
$sock_read_hdl->add($oSocket);
# Block here until message arrives
my ($read_ready) = IO::Select->select($sock_read_hdl, undef, undef, undef);
# Now we are ready to read message. Note: $read_ready->[0] == $oSocket here.
eval { ... } or die $@; # As pointed out by ikegami, thanks.
####
sub read_msg {
my ($sock, $bcount, $buf, $msg) = (shift, 0, '', '');
# Use sysread for stream-oriented sockets
READ_MSG:
while (my $bytes_read = sysread($sock, $buf, 1024)) {
# Handle partial read
$bcount += $bytes_read;
$msg .= $buf;
}
# Just in case
redo READ_MSG if $! =~ /Resource temporarily unavailable/;
# All other errors trigger unconditional return with error
return ($msg, $bcount, $!) if ($!);
# Return success
return ($msg, $bcount, '');
}
##
##
...
# Instead of eval block use our new function call
my ($msg, $bcount, $error) = read_msg($read_ready->[0]);
# Check for errors and empty messages
die $error, "\n" if ($error);
die "Nothing received!\n" if ($bcount == 0);
...