Module: Zerg::Support::EventMachine::FrameProtocol
- Included in:
- ObjectProtocol
- Defined in:
- lib/zerg_support/event_machine/frame_protocol.rb
Overview
Event Machine protocol for sending and receiving discrete-sized frames
Class Method Summary collapse
-
.decode_natural(string) ⇒ Object
:nodoc: Decodes a natural (non-negative) integer from a string.
-
.encode_natural(number) ⇒ Object
:nodoc: Encodes a natural (non-negative) integer into a string.
Instance Method Summary collapse
-
#receive_data(data) ⇒ Object
:nodoc: This is called by Event Machine when TCP stream data is available.
-
#receive_frame(frame_data) ⇒ Object
Override to process incoming frames.
-
#send_frame(frame_data) ⇒ Object
Sends a frame via the underlying Event Machine TCP stream.
Class Method Details
.decode_natural(string) ⇒ Object
:nodoc: Decodes a natural (non-negative) integer from a string.
55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/zerg_support/event_machine/frame_protocol.rb', line 55 def self.decode_natural(string) number = 0 multiplier = 1 string.each_byte do |byte| more, number_bits = byte.divmod 0x80 number += number_bits * multiplier break if more == 0 multiplier *= 0x80 end return number end |
.encode_natural(number) ⇒ Object
:nodoc: Encodes a natural (non-negative) integer into a string.
44 45 46 47 48 49 50 51 52 |
# File 'lib/zerg_support/event_machine/frame_protocol.rb', line 44 def self.encode_natural(number) string = '' loop do number, byte = number.divmod(0x80) string << (byte | ((number > 0) ? 0x80 : 0x00)) break if number == 0 end string end |
Instance Method Details
#receive_data(data) ⇒ Object
:nodoc: This is called by Event Machine when TCP stream data is available.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/zerg_support/event_machine/frame_protocol.rb', line 7 def receive_data(data) @frame_protocol_varsize ||= '' i = 0 loop do while @frame_protocol_buffer.nil? and i < data.size @frame_protocol_varsize << data[i] if (data[i] & 0x80) == 0 @frame_protocol_bytes_left = FrameProtocol.decode_natural @frame_protocol_varsize @frame_protocol_buffer = '' end i += 1 end return if @frame_protocol_buffer.nil? break if @frame_protocol_bytes_left > data.size - i receive_frame @frame_protocol_buffer + data[i, @frame_protocol_bytes_left] @frame_protocol_varsize, @frame_protocol_buffer = '', nil i += @frame_protocol_bytes_left end @frame_protocol_buffer << data[i..-1] @frame_protocol_bytes_left -= data.size-i end |
#receive_frame(frame_data) ⇒ Object
Override to process incoming frames.
35 |
# File 'lib/zerg_support/event_machine/frame_protocol.rb', line 35 def receive_frame(frame_data); end |
#send_frame(frame_data) ⇒ Object
Sends a frame via the underlying Event Machine TCP stream.
38 39 40 41 |
# File 'lib/zerg_support/event_machine/frame_protocol.rb', line 38 def send_frame(frame_data) encoded_length = FrameProtocol.encode_natural(frame_data.length) send_data encoded_length + frame_data end |