title: Object-oriented networking
body: <p>I've written a number of networking systems and have a good idea of how networking works.  However I always end up having a packet receive function which is a giant switch statement.  This is beginning to get to me.  I'd far rather a nice elegant object-oriented way to handle receiving packets but every time I try to come up with a good solution I always end up coming up short.</p>
  
  <p>For example lets say you have a network server.  It is simply waiting there for responses.  A packet comes in and the server needs to validate the packet and then it needs to decide how to handle it.  </p>
  
  <p>At the moment I have been doing this by switching on the packet id in the header and then having a huge bunch of function calls that handle each packet type.  With complicated networking systems this results in a monolithic switch statement and I really don't like handling it this way.  One way I've considered is to use a map of handler classes.  I can then pass the packet to the relevant class and handle the incoming data.  The problem I have with this is that I need some way to "register" each packet handler with the map.  This means, generally, I need to create a static copy of the class and then in the constructor register it with the central packet handler.  While this works it really seems like an inelegant and fiddly way of handling it.</p>
  
  <p><strong>Edit</strong>: Equally it would be ideal to have a nice system that works both ways.  ie a class structure that easily handles sending the same packet types as receiving them (through different functions obviously).</p>
  
  <p>Can anyone point me towards a better way to handle incoming packets?  Links and useful information are much appreciated!</p>
  
  <p>Apologies if I haven't described my problem well as my inability to describe it well is also the reason I've never managed to come up with a solution.</p>