ferencd@0: require 'net/protocol' ferencd@0: ferencd@0: module Net ferencd@0: class HTTP < Protocol ferencd@0: module Server ferencd@0: # ferencd@0: # Handles reading and writing to raw HTTP streams. ferencd@0: # ferencd@0: # @since 0.2.0 ferencd@0: # ferencd@0: class Stream ferencd@0: ferencd@0: include Enumerable ferencd@0: ferencd@0: # The raw socket of the stream. ferencd@0: attr_reader :socket ferencd@0: ferencd@0: # ferencd@0: # Creates a new stream. ferencd@0: # ferencd@0: # @param [TCPSocket] socket ferencd@0: # The raw socket that will be read/write to. ferencd@0: # ferencd@0: # @since 0.2.0 ferencd@0: # ferencd@0: def initialize(socket) ferencd@0: @socket = socket ferencd@0: end ferencd@0: ferencd@0: # ferencd@0: # Reads data from the stream. ferencd@0: # ferencd@0: # @param [Integer] length ferencd@0: # The number of bytes to read. ferencd@0: # ferencd@0: # @param [#<<] buffer ferencd@0: # The optional buffer to append the data to. ferencd@0: # ferencd@0: # @return [String, nil] ferencd@0: # A chunk from the stream. ferencd@0: # ferencd@0: # @since 0.2.0 ferencd@0: # ferencd@0: def read(length=4096,buffer='') ferencd@0: @socket.read(length,buffer) ferencd@0: end ferencd@0: ferencd@0: # ferencd@0: # Reads each chunk from the stream. ferencd@0: # ferencd@0: # @yield [chunk] ferencd@0: # The given block will be passed each chunk. ferencd@0: # ferencd@0: # @yieldparam [String] chunk ferencd@0: # A chunk from the stream. ferencd@0: # ferencd@0: # @return [Enumerator] ferencd@0: # If no block is given, an Enumerator will be returned. ferencd@0: # ferencd@0: # @since 0.2.0 ferencd@0: # ferencd@0: def each ferencd@0: return enum_for unless block_given? ferencd@0: ferencd@0: while (chunk = read) ferencd@0: yield chunk ferencd@0: end ferencd@0: end ferencd@0: ferencd@0: # ferencd@0: # Reads the entire body. ferencd@0: # ferencd@0: # @return [String] ferencd@0: # The complete body. ferencd@0: # ferencd@0: # @since 0.2.0 ferencd@0: # ferencd@0: def body ferencd@0: buffer = '' ferencd@0: ferencd@0: each { |chunk| buffer << chunk } ferencd@0: return buffer ferencd@0: end ferencd@0: ferencd@0: # ferencd@0: # Writes data to the stream. ferencd@0: # ferencd@0: # @param [String] data ferencd@0: # The data to write to the stream. ferencd@0: # ferencd@0: # @return [Integer] ferencd@0: # The length of the data written. ferencd@0: # ferencd@0: # @since 0.2.0 ferencd@0: # ferencd@0: def write(data) ferencd@0: result = @socket.write(data) ferencd@0: ferencd@0: @socket.flush ferencd@0: return result ferencd@0: end ferencd@0: ferencd@0: # ferencd@0: # @see #write ferencd@0: # ferencd@0: # @since 0.2.0 ferencd@0: # ferencd@0: def <<(data) ferencd@0: write(data) ferencd@0: end ferencd@0: ferencd@0: # ferencd@0: # Closes the stream. ferencd@0: # ferencd@0: # @since 0.2.0 ferencd@0: # ferencd@0: def close ferencd@0: end ferencd@0: ferencd@0: end ferencd@0: end ferencd@0: end ferencd@0: end