def receive_data data
while data and data.length > 0
case @read_state
when :base
@data = ""
@headers = []
@content_length = nil
@content = ""
@status = nil
@read_state = :header
@connection_close = nil
when :header
ary = data.split( /\r?\n/m, 2 )
if ary.length == 2
data = ary.last
if ary.first == ""
if (@content_length and @content_length > 0) || @connection_close
@read_state = :content
else
dispatch_response
@read_state = :base
end
else
@headers << ary.first
if @headers.length == 1
parse_response_line
elsif ary.first =~ /\Acontent-length:\s*/i
@content_length ||= $'.to_i
elsif ary.first =~ /\Aconnection:\s*close/i
@connection_close = true
end
end
else
@data << data
data = ""
end
when :content
if @content_length
bytes_needed = @content_length - @content.length
@content += data[0, bytes_needed]
data = data[bytes_needed..-1] || ""
if @content_length == @content.length
dispatch_response
@read_state = :base
end
else
@content << data
data = ""
end
end
end
end