# class Listen::TCP::Message

### Constants

HEADER_FORMAT
HEADER_SIZE
PAYLOAD_FORMAT

### Attributes

body[R]
object[R]
payload[R]
size[R]

### Public Class Methods

from_buffer(buffer) click to toggle source

Extracts a message from given buffer

    # File lib/listen/tcp/message.rb, line 36
    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

new(*args) click to toggle source

Initializes a new message

@param [Object] object to initialize message with

    # File lib/listen/tcp/message.rb, line 16
    def initialize(*args)
      self.object = args
    end

### Public Instance Methods

object=(obj) click to toggle source

Generates message size and payload for given object

    # File lib/listen/tcp/message.rb, line 21
    def object=(obj)
      @object = obj
      @body = JSON.generate(@object)
      @size = @body.bytesize
      @payload = [@size, @body].pack(PAYLOAD_FORMAT)
    end

payload=(payload) click to toggle source

Extracts message size and loads object from given payload

    # File lib/listen/tcp/message.rb, line 29
    def payload=(payload)
      @payload = payload
      @size, @body = @payload.unpack(PAYLOAD_FORMAT)
      @object = JSON.parse(@body)
    end