Class: Listen::TCP::Message

Inherits:
Object
  • Object
show all
Defined in:
lib/listen/tcp/message.rb

Constant Summary collapse

HEADER_SIZE =
4
HEADER_FORMAT =
'N'
PAYLOAD_FORMAT =
"#{HEADER_FORMAT}a*"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object = nil) ⇒ Message

Initializes a new message

Parameters:

  • object (Object) (defaults to: nil)

    to initialize message with



17
18
19
# File 'lib/listen/tcp/message.rb', line 17

def initialize(object = nil)
  self.object = object if object
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



7
8
9
# File 'lib/listen/tcp/message.rb', line 7

def body
  @body
end

#objectObject

Returns the value of attribute object.



7
8
9
# File 'lib/listen/tcp/message.rb', line 7

def object
  @object
end

#payloadObject

Returns the value of attribute payload.



7
8
9
# File 'lib/listen/tcp/message.rb', line 7

def payload
  @payload
end

#sizeObject (readonly)

Returns the value of attribute size.



7
8
9
# File 'lib/listen/tcp/message.rb', line 7

def size
  @size
end

Class Method Details

.from_buffer(buffer) ⇒ Object

Extracts a message from given buffer



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/listen/tcp/message.rb', line 37

def self.from_buffer(buffer)
  if buffer.bytesize > HEADER_SIZE
    size = buffer.unpack(HEADER_FORMAT).first
    payload_size = HEADER_SIZE + size
    if buffer.bytesize >= payload_size
      payload = buffer.slice!(0...payload_size)
      new.tap do |message|
        message.payload = payload
      end
    end
  end
end