Class: Net::HTTP::Server::ChunkedStream
- Defined in:
- lib/net/http/server/chunked_stream.rb
Overview
Handles reading and writing to Chunked Transfer-Encoded streams.
Instance Attribute Summary
Attributes inherited from Stream
Instance Method Summary collapse
-
#close ⇒ Object
Closes the chunked stream.
-
#initialize(socket) ⇒ ChunkedStream
constructor
Initializes the chunked stream.
-
#read(length = 4096, buffer = '') ⇒ String?
Reads a chunk from the stream.
-
#write(data) ⇒ Integer
Writes data to the chunked stream.
Methods inherited from Stream
Constructor Details
#initialize(socket) ⇒ ChunkedStream
Initializes the chunked stream.
22 23 24 25 26 |
# File 'lib/net/http/server/chunked_stream.rb', line 22 def initialize(socket) super(socket) @buffer = '' end |
Instance Method Details
#close ⇒ Object
Closes the chunked stream.
106 107 108 109 110 |
# File 'lib/net/http/server/chunked_stream.rb', line 106 def close # last chunk @socket.write("0\r\n\r\n") @socket.flush end |
#read(length = 4096, buffer = '') ⇒ String?
Reads a chunk from the stream.
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/net/http/server/chunked_stream.rb', line 44 def read(length=4096,buffer='') unless buffer.respond_to?(:<<) raise(ArgumentError,"buffer must respond to #<<") end until @buffer.length >= length length_line = @socket.readline("\r\n").chomp chunk_length = length_line.split(';',2).first.to_i(16) # read the chunk @buffer << @socket.read(chunk_length) # chomp the terminating CRLF @socket.read(2) # end-of-stream break if chunk_length == 0 end # clear the buffer before appending buffer.replace('') unless @buffer.empty? # empty a slice of the buffer buffer << @buffer.slice!(0,length) return buffer end end |
#write(data) ⇒ Integer
Writes data to the chunked stream.
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/net/http/server/chunked_stream.rb', line 84 def write(data) length = data.length # do not write empty chunks unless length == 0 # write the chunk length @socket.write("%X\r\n" % length) # write the data @socket.write(data) @socket.write("\r\n") @socket.flush end return length end |