Class: PacketIO::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/packet_io/io_listener.rb

Overview

a chainable IO-Listener that provides two methods:

#on_data

a callback that is called whenever a message is received

#write

can be called so send messages to the underlying IO

when overriding this class, you need to implement two methods:

#receive

is called from an underlying IO whenever a message is received the message can be handled. Call #forward to propagate

#write

transform/encode a message before sending it. Call super to propagate

See LineBasedProtocol for a toy implementation which strips newlines and only forwards complete lines.

Direct Known Subclasses

IOListener, LineBasedProtocol

Instance Method Summary collapse

Constructor Details

#initialize(read, write = read) ⇒ Base

Returns a new instance of Base.

Parameters:

  • read (Base, #on_data)

    data source

  • write (Base, IO, #write) (defaults to: read)

    object where messages are written to



27
28
29
30
31
# File 'lib/packet_io/io_listener.rb', line 27

def initialize(read, write = read)
  @reader, @writer = read, write
  @on_data = nil
  @reader.on_data { |*data| receive(*data) } if @reader.respond_to?(:on_data)
end

Instance Method Details

#<<(*args) ⇒ Object

See Also:



49
50
51
# File 'lib/packet_io/io_listener.rb', line 49

def <<(*args)
  write(*args)
end

#on_data {|*args| ... } ⇒ self

register a block, to be run whenever the protocol implementation receives data (by calling #forward)

this is used to chain protocol layers together

Yields:

  • (*args)

    called whenever the protocol implementaion calls #forward

Yield Returns:

  • (nil)

Returns:

  • (self)


42
43
44
45
# File 'lib/packet_io/io_listener.rb', line 42

def on_data(&block)
  @on_data = block
  self
end

#write(*args) ⇒ Object

write data to underlying interface. override if data needs to be preprocessed



55
56
57
# File 'lib/packet_io/io_listener.rb', line 55

def write(*args)
  @writer.<<(*args) if @writer
end