Thursday, September 07, 2006
Code Snippet: Using non-blocking threads in Ruby 1.8.5
Non-blocking IO has made a huge difference to network IO in Ruby. I have a pen testing script that runs in two minutes where the C# version takes about an hour!
So here is how to use non blocking IO in the simplest form:
require 'socket'
socket = TCPSocket.new("www.pentester.com.au",80)
socket.write_nonblock("HEAD / HTTP/1.0\n\n")
IO.select [socket]
buffer = ""
begin
while chunk = socket.read_nonblock(512)
buffer = buffer + chunk
end
rescue
end
socket.close() if socket and !socket.closed?
$stdout.puts(buffer)
So here is how to use non blocking IO in the simplest form:
require 'socket'
socket = TCPSocket.new("www.pentester.com.au",80)
socket.write_nonblock("HEAD / HTTP/1.0\n\n")
IO.select [socket]
buffer = ""
begin
while chunk = socket.read_nonblock(512)
buffer = buffer + chunk
end
rescue
end
socket.close() if socket and !socket.closed?
$stdout.puts(buffer)