Class: SSE::HTTPResponseReader

Inherits:
Object
  • Object
show all
Defined in:
lib/sse_client/streaming_http.rb

Overview

Used internally to read the HTTP response, either all at once or as a stream of text lines. Incoming data is fed into an instance of HTTPTools::Parser, which gives us the header and chunks of the body via callbacks.

Constant Summary collapse

DEFAULT_CHUNK_SIZE =
10000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket, read_timeout) ⇒ HTTPResponseReader

Returns a new instance of HTTPResponseReader.



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/sse_client/streaming_http.rb', line 121

def initialize(socket, read_timeout)
  @socket = socket
  @read_timeout = read_timeout
  @parser = HTTPTools::Parser.new
  @buffer = ""
  @done = false
  @lock = Mutex.new

  # Provide callbacks for the Parser to give us the headers and body. This has to be done
  # before we start piping any data into the parser.
  have_headers = false
  @parser.on(:header) do
    have_headers = true
  end
  @parser.on(:stream) do |data|
    @lock.synchronize { @buffer << data }  # synchronize because we're called from another thread in Socketry
  end
  @parser.on(:finish) do
    @lock.synchronize { @done = true }
  end

  # Block until the status code and headers have been successfully read.
  while !have_headers
    raise EOFError if !read_chunk_into_buffer
  end
  @headers = Hash[@parser.header.map { |k,v| [k.downcase, v] }]
  @status = @parser.status_code
end

Instance Attribute Details

#headersObject (readonly)

Returns the value of attribute headers.



119
120
121
# File 'lib/sse_client/streaming_http.rb', line 119

def headers
  @headers
end

#statusObject (readonly)

Returns the value of attribute status.



119
120
121
# File 'lib/sse_client/streaming_http.rb', line 119

def status
  @status
end

Instance Method Details

#read_allObject



160
161
162
163
164
# File 'lib/sse_client/streaming_http.rb', line 160

def read_all
  while read_chunk_into_buffer
  end
  @buffer
end

#read_linesObject



150
151
152
153
154
155
156
157
158
# File 'lib/sse_client/streaming_http.rb', line 150

def read_lines
  Enumerator.new do |gen|
    loop do
      line = read_line
      break if line.nil?
      gen.yield line
    end
  end
end