Class: RCon::Client::Packet

Inherits:
Data
  • Object
show all
Defined in:
lib/rcon/client/packet.rb,
lib/rcon/client/packet.rb

Overview

Immutable value object representing a single Source RCON packet.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id:, type:, body: "") ⇒ Packet

Returns a new instance of Packet.



22
23
24
25
# File 'lib/rcon/client/packet.rb', line 22

def initialize(id:, type:, body: "")
  body = body.b
  super
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body

Returns:

  • (Object)

    the current value of body



5
6
7
# File 'lib/rcon/client/packet.rb', line 5

def body
  @body
end

#idObject (readonly)

Returns the value of attribute id

Returns:

  • (Object)

    the current value of id



5
6
7
# File 'lib/rcon/client/packet.rb', line 5

def id
  @id
end

#typeObject (readonly)

Returns the value of attribute type

Returns:

  • (Object)

    the current value of type



5
6
7
# File 'lib/rcon/client/packet.rb', line 5

def type
  @type
end

Class Method Details

.decode(data) ⇒ Packet

Parameters:

  • data (String)

    raw packet bytes including the size field

Returns:



15
16
17
18
19
20
# File 'lib/rcon/client/packet.rb', line 15

def self.decode(data)
  _size, id, type = data.unpack("l<l<l<")
  # data layout: size(4) + id(4) + type(4) + body + null(1) + empty-string(1)
  body = data.byteslice(12, data.bytesize - 14)
  self[id:, type:, body:]
end

Instance Method Details

#encodeString

Returns binary-encoded packet.

Returns:

  • (String)

    binary-encoded packet

Raises:

  • (Error)

    if body exceeds 511 bytes



29
30
31
32
33
34
# File 'lib/rcon/client/packet.rb', line 29

def encode
  raise Error, "body too long (#{body.bytesize} > #{BODY_BYTE_LIMIT})" if body.bytesize > BODY_BYTE_LIMIT

  size = 8 + body.bytesize + 2 # id(4) + type(4) + body + null(1) + empty-string(1)
  [size, id, type].pack("l<l<l<") + body + "\x00\x00".b
end