8bb326c6aeddd50cdabca0716a4233b6

Just looking for better architecture to handle data from sockets, parsing it, splitting into packets, working with packet :)

# start here, on_data called where thereis data on a socket(data can be partial-packet)
def on_data bytes
  @stream << bytes
  parse_stream
end

def parse_stream
  # looking for FULL packet in stream
  # if there is full packet, then assign his bytes to `bytes`

  # got packet, calling parse
  if full
    drop_packet = parse_packet(bytes)
  end
  
  if drop_packet
    "" # send empty
  else
    bytes # unmodified packet
  end
end

def parse_packet bytes
  # instantiate class for packet-parsing, based on header of `bytes`
  packet = Packets.detect(bytes)
  # after this moment, `bytes` is modified to store only data-part without header & size parts
  
  if packet
    # currently, deserialize return "true" or "false"
    Hooks.fire(:pre_packet)
    drop_packet = packet.deserialize(bytes)
    Hooks.fire(:post_packet, packet, drop_packet) # in this hook, i want to modify/do some action
                                                  # and change `drop_packet` variable, i.e. replace credentials
                                                  # replaced packets are sent in hook
    
    return drop_packet
  end
  
  false
end

# Hook example
Hooks.on(:post_packet) do |hook, packet, drop_packet|
  if IdentityMessage === packet
    $server.send(IdentityMessage.new('user', 'password'))
  end
  
  drop_packet = true  # and yes, this is don't work, because drop_packet
                      # now referencing to another memory space
                      # thinking about to change it to String class, and use `replace` method...
end

Refactorings

No refactoring yet !

8bb326c6aeddd50cdabca0716a4233b6

Bubonic Pestilence

May 7, 2011, May 07, 2011 04:58, permalink

No rating. Login to rate!

1st solution for drop_packet by Mon_Ouie

# add instance variable for packet class
packet.drop(true)
8cb291a5579411f1fe17b3babb0928bb

Stone

July 30, 2011, July 30, 2011 04:09, permalink

No rating. Login to rate!

Yeah, that's the tciket, sir or ma'am

8cb291a5579411f1fe17b3babb0928bb

Stone

July 30, 2011, July 30, 2011 04:09, permalink

No rating. Login to rate!

Yeah, that's the tciket, sir or ma'am

8cb291a5579411f1fe17b3babb0928bb

Stone

July 30, 2011, July 30, 2011 04:10, permalink

No rating. Login to rate!

Yeah, that's the tciket, sir or ma'am

Your refactoring





Format Copy from initial code

or Cancel