Created
June 8, 2015 18:48
-
-
Save jvranish/f00e9ffe19841a3e162b to your computer and use it in GitHub Desktop.
ruby read with timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def read_with_timeout(io_like, read_len, timeout) | |
timeout_time = Time.now + timeout | |
data = "" | |
loop do | |
begin | |
result = io_like.read_nonblock(read_len - data.length) | |
puts data | |
data += result | |
if block_given? | |
bd = yield data | |
return [:matched, bd] if !bd.nil? | |
end | |
return [:length, data] if data.length == read_len | |
rescue EOFError | |
return [:eof, data] | |
rescue IO::WaitReadable | |
time_remaining = timeout_time - Time.now | |
return [:timeout, data] if time_remaining < 0 | |
IO.select([io_like], nil, nil, time_remaining) | |
retry | |
rescue IO::WaitWritable | |
time_remaining = timeout_time - Time.now | |
return [:timeout, data] if time_remaining < 0 | |
IO.select(nil, [io_like], nil, time_remaining) | |
retry | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment