From 34cbf4411bafb2abc526467126ad779b54ce9f00 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Sat, 19 Dec 2015 13:51:04 -0800 Subject: [PATCH] Send headers and body in one write if possible This change tries to avoid a pathological case with Nagle's algorithm where two small writes that would fit in a single TCP packet are performed in a row (headers and body). Instead, it tries to perform a single write if possible. --- lib/http/request/writer.rb | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/lib/http/request/writer.rb b/lib/http/request/writer.rb index a050428b..05b7c81b 100644 --- a/lib/http/request/writer.rb +++ b/lib/http/request/writer.rb @@ -36,8 +36,9 @@ def add_headers # Stream the request to a socket def stream - send_request_header - send_request_body + add_headers + add_body_type_headers + send_request end # Send headers needed to connect through proxy @@ -64,23 +65,24 @@ def join_headers @request_header.join(CRLF) + (CRLF) * 2 end - def send_request_header - add_headers - add_body_type_headers + def send_request + headers = join_headers - write(join_headers) - end + case @body + when NilClass + write(headers) + when String + write(headers << @body) + when Enumerable + write(headers) - def send_request_body - if @body.is_a?(String) - write(@body) - elsif @body.is_a?(Enumerable) @body.each do |chunk| write(chunk.bytesize.to_s(16) << CRLF) write(chunk << CRLF) end write(CHUNKED_END) + else fail TypeError, "invalid body type: #{@body.class}" end end