Class: Kward::RPC::Transport

Inherits:
Object
  • Object
show all
Defined in:
lib/kward/rpc/transport.rb

Instance Method Summary collapse

Constructor Details

#initialize(input:, output:) ⇒ Transport

Returns a new instance of Transport.



6
7
8
9
10
# File 'lib/kward/rpc/transport.rb', line 6

def initialize(input:, output:)
  @input = input
  @output = output
  @write_mutex = Mutex.new
end

Instance Method Details

#read_messageObject



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/kward/rpc/transport.rb', line 12

def read_message
  headers = read_headers
  return nil unless headers

  length = headers["content-length"].to_i
  raise "Missing Content-Length header" if length <= 0

  body = @input.read(length)
  raise "Unexpected EOF while reading JSON-RPC body" unless body && body.bytesize == length

  JSON.parse(body)
end

#write_message(message) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/kward/rpc/transport.rb', line 25

def write_message(message)
  body = JSON.generate(message)
  @write_mutex.synchronize do
    @output.write("Content-Length: #{body.bytesize}\r\n\r\n")
    @output.write(body)
    @output.flush if @output.respond_to?(:flush)
  end
end