class TellaPeer::Message

Constants

HEADER_PACKER

Attributes

ip[W]
port[W]
text[W]
ttl[W]
hops[W]
message_id[W]
payload_length[W]
recv_ip[RW]
recv_port[RW]
ttl[W]

Public Class Methods

ip() click to toggle source
# File lib/tella_peer/message.rb, line 7
def ip
  @ip ||= [127, 0, 0, 1]
end
key() click to toggle source
# File lib/tella_peer/message.rb, line 19
def key
  "#{ip.join('.')}:#{port}"
end
new(header = nil, body = '') click to toggle source
# File lib/tella_peer/message.rb, line 29
def initialize(header = nil, body = '')
  if header
    self.message_id     = header[0..15].map(&:chr).join
    self.ttl            = header[17]
    self.hops           = header[18]
    self.payload_length = header[19]
  end
end
port() click to toggle source
# File lib/tella_peer/message.rb, line 10
def port
  @port ||= 9000
end
text() click to toggle source
# File lib/tella_peer/message.rb, line 16
def text
  @text ||= UUID.new.generate
end
ttl() click to toggle source
# File lib/tella_peer/message.rb, line 13
def ttl
  @ttl ||= 5
end
unpack(socket, ip, port) click to toggle source
# File lib/tella_peer/message.rb, line 81
def self.unpack(socket, ip, port)
  header = socket.read(23)
  return if header.nil?
  header = header.unpack(HEADER_PACKER)
  body   = socket.read(header.last)

  message = case header[16]
  when -1
    Message.new(header,body)
  when 0
    Ping.new(header,body)
  when 1
    Pong.new(header,body)
  when 2
    Query.new(header,body)
  when 3
    Reply.new(header,body)
  else
    throw "Unknown Type #{header[16]}"
  end

  message.recv_ip = ip
  message.recv_port = port
  message
end

Public Instance Methods

hops() click to toggle source
# File lib/tella_peer/message.rb, line 50
def hops
  @hops ||= 0
end
increment!() click to toggle source
# File lib/tella_peer/message.rb, line 70
def increment!
  self.ttl  += -1
  self.hops +=  1
  self
end
message_id() click to toggle source
# File lib/tella_peer/message.rb, line 38
def message_id
  @message_id ||= UUID.new.generate(:compact)[0..15]
end
pack() click to toggle source
# File lib/tella_peer/message.rb, line 76
def pack
  id = message_id.chars.map { |i| i.ord }
  ((id << type << ttl << hops << payload_length) + payload).pack(HEADER_PACKER + payload_packer)
end
payload() click to toggle source
# File lib/tella_peer/message.rb, line 62
def payload
  []
end
payload_length() click to toggle source
# File lib/tella_peer/message.rb, line 58
def payload_length
  @payload_length ||= 0
end
payload_packer() click to toggle source
# File lib/tella_peer/message.rb, line 66
def payload_packer
  ''
end
transmitable?() click to toggle source
# File lib/tella_peer/message.rb, line 54
def transmitable?
  ttl > 0
end
ttl() click to toggle source
# File lib/tella_peer/message.rb, line 46
def ttl
  @ttl ||= Message.ttl
end
type() click to toggle source
# File lib/tella_peer/message.rb, line 42
def type
  MessageTypes::UNKNOWN
end