Class: Net::HTTP::Server::ChunkedStream

Inherits:
Stream
  • Object
show all
Defined in:
lib/net/http/server/chunked_stream.rb

Overview

Handles reading and writing to Chunked Transfer-Encoded streams.

Since:

  • 0.2.0

Instance Attribute Summary

Attributes inherited from Stream

#socket

Instance Method Summary collapse

Methods inherited from Stream

#<<, #body, #each

Constructor Details

#initialize(socket) ⇒ ChunkedStream

Initializes the chunked stream.

Parameters:

  • socket (#read, #write, #flush)

    The socket to read from and write to.

Since:

  • 0.2.0



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

#closeObject

Closes the chunked stream.

Since:

  • 0.2.0



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.

Parameters:

  • length (Integer) (defaults to: 4096)
  • buffer (#<<) (defaults to: '')

    The optional buffer to append the data to.

Returns:

  • (String, nil)

    A chunk from the stream.

Raises:

  • (ArgumentError)

    The buffer did not respond to #<<.

Since:

  • 0.2.0



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.

Parameters:

  • data (String)

    The data to write to the stream.

Returns:

  • (Integer)

    The length of the data written.

Since:

  • 0.2.0



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