Class: Distributor::Multiplexer
- Inherits:
-
Object
- Object
- Distributor::Multiplexer
- Defined in:
- lib/distributor/multiplexer.rb
Instance Method Summary collapse
- #close(ch) ⇒ Object
- #generate_id ⇒ Object
-
#initialize(output) ⇒ Multiplexer
constructor
A new instance of Multiplexer.
- #input(io) ⇒ Object
- #output(ch, data) ⇒ Object
- #reader(ch) ⇒ Object
- #reserve(ch = nil) ⇒ Object
- #writer(ch) ⇒ Object
Constructor Details
#initialize(output) ⇒ Multiplexer
Returns a new instance of Multiplexer.
7 8 9 10 11 12 13 |
# File 'lib/distributor/multiplexer.rb', line 7 def initialize(output) @output = output @readers = Hash.new { |hash,key| hash[key] = StringIO.new } @writers = Hash.new { |hash,key| hash[key] = StringIO.new } @output.sync = true end |
Instance Method Details
#close(ch) ⇒ Object
43 44 45 46 |
# File 'lib/distributor/multiplexer.rb', line 43 def close(ch) output 0, Distributor::OkJson.encode({ "command" => "close", "ch" => ch }) rescue IOError end |
#generate_id ⇒ Object
48 49 50 |
# File 'lib/distributor/multiplexer.rb', line 48 def generate_id id = "#{Time.now.to_f}-#{rand(10000)}" end |
#input(io) ⇒ Object
30 31 32 33 34 35 36 |
# File 'lib/distributor/multiplexer.rb', line 30 def input(io) ch, data = Distributor::Packet.parse(io) return if ch.nil? writer(ch).write data rescue IOError output 0, Distributor::OkJson.encode({ "command" => "close", "ch" => ch }) end |
#output(ch, data) ⇒ Object
38 39 40 41 |
# File 'lib/distributor/multiplexer.rb', line 38 def output(ch, data) Distributor::Packet.write(@output, ch, data) rescue Errno::EPIPE end |
#reader(ch) ⇒ Object
22 23 24 |
# File 'lib/distributor/multiplexer.rb', line 22 def reader(ch) @readers[ch] end |
#reserve(ch = nil) ⇒ Object
15 16 17 18 19 20 |
# File 'lib/distributor/multiplexer.rb', line 15 def reserve(ch=nil) ch ||= @readers.keys.length raise "channel already taken: #{ch}" if @readers.has_key?(ch) @readers[ch], @writers[ch] = IO.pipe ch end |
#writer(ch) ⇒ Object
26 27 28 |
# File 'lib/distributor/multiplexer.rb', line 26 def writer(ch) @writers[ch] end |