161: def receive_data data
162: while data and data.length > 0
163: case @read_state
164: when :base
165:
166: @data = ""
167: @headers = []
168: @content_length = nil
169: @content = ""
170: @status = nil
171: @read_state = :header
172: @connection_close = nil
173: when :header
174: ary = data.split( /\r?\n/m, 2 )
175: if ary.length == 2
176: data = ary.last
177: if ary.first == ""
178: if (@content_length and @content_length > 0) || @connection_close
179: @read_state = :content
180: else
181: dispatch_response
182: @read_state = :base
183: end
184: else
185: @headers << ary.first
186: if @headers.length == 1
187: parse_response_line
188: elsif ary.first =~ /\Acontent-length:\s*/i
189:
190:
191:
192:
193:
194:
195: @content_length ||= $'.to_i
196: elsif ary.first =~ /\Aconnection:\s*close/i
197: @connection_close = true
198: end
199: end
200: else
201: @data << data
202: data = ""
203: end
204: when :content
205:
206:
207:
208:
209:
210: if @content_length
211: bytes_needed = @content_length - @content.length
212: @content += data[0, bytes_needed]
213: data = data[bytes_needed..-1] || ""
214: if @content_length == @content.length
215: dispatch_response
216: @read_state = :base
217: end
218: else
219: @content << data
220: data = ""
221: end
222: end
223: end
224: end