Class: Lobster::Network::Packet

Inherits:
Object
  • Object
show all
Defined in:
lib/lobster/network/packet.rb

Overview

Self-contained network data. Packets can carry a maximum payload of 64 KB.

Constant Summary collapse

HEADER_SIZE =

Number of bytes in the header of all packets.

2
MAX_PAYLOAD_SIZE =

Number of bytes that a packet can hold in its payload.

2 ** (HEADER_SIZE * 8)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(payload) ⇒ Packet

Creates a new packet.


20
21
22
23
24
25
26
# File 'lib/lobster/network/packet.rb', line 20

def initialize(payload)
  fail ArgumentError unless payload.is_a?(String)
  fail ArgumentError if payload.bytesize > MAX_PAYLOAD_SIZE

  @payload = payload.dup
  @payload.freeze
end

Instance Attribute Details

#payloadString (readonly)

Retrieves the raw payload data contained in the packet.


16
17
18
# File 'lib/lobster/network/packet.rb', line 16

def payload
  @payload
end

Class Method Details

.read(input) ⇒ Packet

Reads a packet from an input stream.


37
38
39
40
41
# File 'lib/lobster/network/packet.rb', line 37

def self.read(input)
  payload_size = read_header(input)
  payload      = read_payload(input, payload_size)
  Packet.new(payload)
end

Instance Method Details

#sizeFixnum

Size of the packet's header and payload.


30
31
32
# File 'lib/lobster/network/packet.rb', line 30

def size
  @payload.bytesize + HEADER_SIZE
end

#write(output) ⇒ nil

Writes the packet to an output stream.


65
66
67
68
69
# File 'lib/lobster/network/packet.rb', line 65

def write(output)
  write_header(output)
  write_payload(output)
  nil
end