Class: Librevox::Protocol::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/librevox/protocol/connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(stream) ⇒ Connection

Returns a new instance of Connection.



6
7
8
# File 'lib/librevox/protocol/connection.rb', line 6

def initialize(stream)
  @stream = stream
end

Instance Method Details

#closeObject



38
39
40
41
42
43
44
# File 'lib/librevox/protocol/connection.rb', line 38

def close
  return if @stream.closed?

  @stream.close
rescue Errno::EPIPE, Errno::ECONNRESET
  # Remote end already closed
end

#read_loopObject



27
28
29
30
31
# File 'lib/librevox/protocol/connection.rb', line 27

def read_loop
  while (msg = read_message)
    yield msg
  end
end

#read_messageObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/librevox/protocol/connection.rb', line 10

def read_message
  loop do
    headers = @stream.read_until("\n\n")
    return nil if headers.nil?
    next if headers.empty?

    if headers =~ /Content-Length:\s*(\d+)/i
      length = $1.to_i
      content = length > 0 ? @stream.read_exactly(length) : ""
    else
      content = ""
    end

    return Librevox::Protocol::Response.new(headers, content)
  end
end

#send_message(msg) ⇒ Object



33
34
35
36
# File 'lib/librevox/protocol/connection.rb', line 33

def send_message(msg)
  @stream.write("#{msg}\n\n")
  @stream.flush
end