Skip to content

Instantly share code, notes, and snippets.

@jvranish
Created June 8, 2015 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvranish/f00e9ffe19841a3e162b to your computer and use it in GitHub Desktop.
Save jvranish/f00e9ffe19841a3e162b to your computer and use it in GitHub Desktop.
ruby read with timeout
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