Class: Chingu::GameStates::NetworkState::PacketBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/chingu/game_states/network_state.rb

Instance Method Summary collapse

Constructor Details

#initializePacketBuffer



10
11
12
13
# File 'lib/chingu/game_states/network_state.rb', line 10

def initialize
  @data = '' # Buffered data.
  @length = nil # Length of the next packet. nil if header not read yet.
end

Instance Method Details

#buffer_data(data) ⇒ Object

Add data string to the buffer.



16
17
18
# File 'lib/chingu/game_states/network_state.rb', line 16

def buffer_data(data)
  @data << data
end

#next_packetObject

Call after adding data with #buffer_data until there are no more packets left.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/chingu/game_states/network_state.rb', line 21

def next_packet
  # Read the header to find out the length of the next packet.
  unless @length
    if @data.length >= PACKET_HEADER_LENGTH
      @length = @data[0...PACKET_HEADER_LENGTH].unpack(PACKET_HEADER_FORMAT)[0]
      @data[0...PACKET_HEADER_LENGTH] = ''
    end
  end

  # If there is enough data after the header for the full packet, return it.
  if @length and @length <= @data.length
    begin
      packet =  @data[0...@length]
      @data[0...@length] = ''
      @length = nil
      return packet
    rescue TypeError => ex
      puts "Bad data received:\n#{@data.inspect}"
      raise ex
    end
  else
    return nil
  end
end