lib/tork/client.rb in tork-16.0.0 vs lib/tork/client.rb in tork-17.0.0

- old
+ new

@@ -1,35 +1,51 @@ require 'thread' +require 'json' module Tork module Client - class Receiver < Thread - def initialize *popen_args - (@io = IO.popen(*popen_args)).sync = true - super() { loop { yield @io.gets } } + class Transmitter < Thread + def initialize output_stream + output_stream.sync = true + @outbox = Queue.new + super() do + while command = @outbox.deq + warn "#{$0}(#{$$}): SEND #{command.inspect}" if $DEBUG + output_stream.puts JSON.dump(command) + end + end end - def quit - kill # stop receive loop - Process.kill :SIGTERM, @io.pid - Process.wait @io.pid # reap zombie - @io.close # prevent further I/O + def send command + @outbox.enq command end end - class Transceiver < Receiver - def initialize *popen_args - @io_write_lock = Mutex.new + class Receiver < Thread + def initialize input_stream + super() do + while command = JSON.load(input_stream.gets) + warn "#{$0}(#{$$}): RECV #{command.inspect}" if $DEBUG + yield command + end + end + end + end + + class Transceiver < Transmitter + def initialize *popen_args, &receive_block popen_args[1] = 'w+' - super + @popen_io = IO.popen(*popen_args) + @receiver = Receiver.new(@popen_io, &receive_block) + super @popen_io end - def send command - @io_write_lock.synchronize do - warn "#{caller[2]} SEND #{command.inspect}" if $DEBUG - @io.puts JSON.dump(command) - end + def quit + kill # stop receive loop + Process.kill :SIGTERM, @popen_io.pid + Process.wait @popen_io.pid # reap zombie + @popen_io.close # prevent further I/O end end end end