1

If you are writing a big program with alot of network traffic, where can I best handle my different packets? My packet contains a Packet ID which is connected to a big enum. For example packet LOGIN_AUTH is Packet ID 23.

How can I best seperate the handling of those packets?

  • Make a huge switch statement with all the Packet ID's in there?
  • Make a Packet class and make a extended class for each Packet ID?

I'm making my application in C#, but the question is more general.

Basaa
  • 1,615
  • 4
  • 20
  • 41

1 Answers1

2

Assuming that your objects have an int that defines the package type, it's simple to use an enum to name those integers and to store the handlers in a dictionary like this:

public enum PackageType
{
    LOGIN_AUTH = 23,
    // More enum members here
}

class Package
{
    public int Id { get; set; }
    public PackageType Type { get { return (PackageType) Id; }}
}

class SomeClass
{
    IDictionary<PackageType, Action<Type>> _dictionaryPacketHandlers = new Dictionary<PackageType, Action<Type>>()
    {
        {PackageType.LOGIN_AUTH, package => { /* Logic here */ }},
        // More handlers here
    };
}

Now you can use it like this:

public void SomeMethod(Package package)
{
    _dictionaryPacketHandlers[package.Type](package);
}
lightbricko
  • 2,649
  • 15
  • 21
  • He probably wants to identify the messages based on the enumeration value. Makes sense to only have one type that contains a property for the message identifier for simple network requests etc. – User 12345678 Oct 23 '13 at 19:23
  • What is myPacket exactly? And how do I insert a new packet into the IDictionary? – Basaa Oct 23 '13 at 19:31
  • @ByteBlast, You are correct - I've modified my answer. Bassa, see my modified answer. – lightbricko Oct 23 '13 at 19:39
  • Hmm... Sorry I'm completely lost. I receive data from my socket, with an ID and payload (a string). Say the type is LOGIN_AUTH. How do I handle that packet, and how does the logic in your example have access to my payload? Sorry I really don't understand. I'm coming from Java so I never worked with those Actions, Delegates, Types etc... – Basaa Oct 23 '13 at 19:58